如何在java中解析JSON
我一直在使用org.JSON解析Java中的JSON。我的JSON看起来像这样如何在java中解析JSON,java,android,Java,Android,我一直在使用org.JSON解析Java中的JSON。我的JSON看起来像这样 [{"id" : "1", "type" : "City", "description" : [ "short_description" : "some data", "long_description" : "some data", "postal_code" : "49045", "po
[{"id" : "1",
"type" : "City",
"description" : [ "short_description" : "some data",
"long_description" : "some data",
"postal_code" : "49045",
"population" : "900000",
],
}
],
如何解析标记描述的元素,例如long_description?使用,您只需将其作为库添加到现有项目中,然后执行以下操作:
数据(JSON):
{'foo':'bar','coolness':2.0,'高度':39000,'飞行员':{'firstName':'Buzz','lastName':'Aldrin'},'任务':'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值=新的JSONArray(您的字符串);
对于(int i=0;i
您可以在不使用库的情况下执行此操作-
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();
}
看看这篇文章:参考上一篇文章
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")));