怎样用java解析一个json字符串

Python013

怎样用java解析一个json字符串,第1张

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=0i<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包在附件中

可以使用 commons-jexl3 jar包

示例:

public static void main(String[] args){

String expressionString = "1+2+3"

JexlEngine jexlEngine = new JexlBuilder().create()

JexlExpression jexlExpression = jexlEngine.createExpression(expressionString)

Object evaluate = jexlExpression.evaluate(null)

System.out.println(evaluate)

}

结果: 6

示例2:

来个复杂点的

public static void main(String[] args){

// String expressionString = "1+2+3"

String expressionString = "100*10-(200+300)"

JexlEngine jexlEngine = new JexlBuilder().create()

JexlExpression jexlExpression = jexlEngine.createExpression(expressionString)

Object evaluate = jexlExpression.evaluate(null)

System.out.println(evaluate)

}

结果: 500