![](/img/trans.png)
[英]Parse json field that may be an JSONObject or JSONArray in java
[英]How I may parse JSON in java
我坚持使用org.json在Java中解析JSON。 我的JSON看起来像这样
[{"id" : "1",
"type" : "City",
"description" : [ "short_description" : "some data",
"long_description" : "some data",
"postal_code" : "49045",
"population" : "900000",
],
}
],
我如何解析例如标签描述的元素,例如long_description?
使用json-lib ,您可以简单地将其作为库添加到现有项目中,并执行以下操作:
数据(JSON):
{'foo':'bar','coolness':2.0,'altitude':39000,'pilot':{'firstName':'Buzz','lastName':'Aldrin'},'mission':'apollo 11 '}
解析数据的代码:
import java.io.InputStream;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
public class JsonParsing {
public static void main(String[] args) throws Exception {
InputStream is =
JsonParsing.class.getResourceAsStream( "sample-json.txt");
String jsonTxt = IOUtils.toString( is );
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
double coolness = json.getDouble( "coolness" );
int altitude = json.getInt( "altitude" );
JSONObject pilot = json.getJSONObject("pilot");
String firstName = pilot.getString("firstName");
String lastName = pilot.getString("lastName");
System.out.println( "Coolness: " + coolness );
System.out.println( "Altitude: " + altitude );
System.out.println( "Pilot: " + lastName );
}
}
参考文献:
JSONArray values = new JSONArray(yourstring);
for(int i = 0 ; i < values.length(); i++){
JSONObject object= values.get(i);
JSONArray desc = object.getJSONArray("description");
}
您无需图书馆就可以做到-
try {
JSONTokener tokener = new JSONTokener(yourString);
JSONObject jsonObj = (JSONObject) tokener.nextValue();
String output = jsonObj.getString("streamUrl");
} catch (JSONException e) {
Log.v("Logtag", "Problem in decoding json");
e.printStackTrace();
}
//import java.util.ArrayList;
//import org.bson.Document;
Document root = Document.parse("{ \"foo\" : \"bar\", \"coolness\" : 2.0, \"altitude\" : 39000, \"pilot\" : { \"firstName\" : \"Buzz\", \"lastName\" : \"Aldrin\" }, \"mission\" : \"apollo 11\" }");
System.out.println(((String)root.get("foo")));
System.out.println((root.get("coolness")));
System.out.println((root.get("altitude")));
System.out.println(((String)((Document)root.get("pilot")).get("firstName")));
System.out.println(((String)((Document)root.get("pilot")).get("lastName")));
System.out.println(((String)root.get("mission")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.