怎样用java解析一个json字符串
怎样在后台提取出 bb1 cc1 bb2 cc2? 展开
public static void main(String[] args){
String temp="{'data':{'a':[{'b1':'bb1','c1':'cc1'},{'b2':'bb2','c2':'cc2'}]}}";
JSONObject jodata =JSONObject.fromObject(temp);
JSONObject joa =JSONObject.fromObject(jodata.get("data").toString());
JSONArray ja=JSONArray.fromObject(joa.get("a"));
for(int i=0;i<ja.size();i++){
JSONObject o=ja.getJSONObject(i);
if(o.get("b1")!=null){
System.out.println(o.get("b1"));
}
if(o.get("c1")!=null){
System.out.println(o.get("c1"));
}
if(o.get("b2")!=null){
System.out.println(o.get("b2"));
}
if(o.get("c2")!=null){
System.out.println(o.get("c2"));
}
}
}
注:要包含两个jar包ezmorph-1.0.6.jar和json-lib-2.2.2-jdk15.jar,jar包在附件中
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import sun.org.mozilla.javascript.internal.NativeArray;
import sun.org.mozilla.javascript.internal.NativeObject;
public class Tester
{
public static void main ( String[] args )
{
ScriptEngineManager sem = new ScriptEngineManager ();
ScriptEngine se = sem.getEngineByName ("js");
String jsonstr = "{\"data\":{\"a\":[{\"b1\":\"bb1\",\"c1\":\"cc1\"},{\"b2\":\"bb2\",\"c2\":\"cc2\"}]}}";
try
{
NativeObject no = (NativeObject) se.eval ("(" + jsonstr + ")");
NativeObject data = (NativeObject) no.get ("data", null);
NativeArray na = (NativeArray) data.get ("a", null);
for ( int i = 0; i < na.getLength (); i++ )
{
NativeObject object = (NativeObject) na.get (i, null);
Object[] ids = object.getIds ();
for ( int j = 0; j < ids.length; j++ )
{
System.out.println (object.get (ids[j].toString (), null));
}
}
}
catch (ScriptException e)
{
e.printStackTrace ();
}
}
}