开发者

JSON Parsing in Android [duplicate]

This question already has answers here: 开发者_如何学编程 How to parse JSON in Java (36 answers) Closed 7 years ago.

I have searched alot on JSON Parsing in Android, but couldn't quite convinced. Actually got a brief idea but not so clear yet regarding JSON Parsing.

How to implement the JSON Parsing in the Application?


This is a very simple JSON String

{"key1":"value1","key2":"value2"}

In order to get values for it use JSONObject like this :

JSONObject json_obj=new JSONObject(your json string);
String value1=json_obj.getString("key1");
String value2=json_obj.getString("key2");

This is a slightly complex json string

[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}]

In order to extract values from this use JSONArray

JSONArray jArray=new JSONArray(your json string);
for(int i=0;i<(jArray.length());i++)
{
    JSONObject json_obj=jArray.getJSONObject(i);
    String value1=json_obj.getString("key1");
    String value2=json_obj.getString("key2");
}

Hope this helps a bit...........


You can also check out Google's GSON library here. The GSON user guide here has some useful examples to help get you started. I've found GSON to be simple and powerful.


See: http://developer.android.com/reference/org/json/package-summary.html

Primarily, you'll be working with JSONArray and JSONObject.

Simple example:

    try {
        JSONObject json = new JSONObject(jsonString);
        int someInt = json.getInt("someInt");
        String someString = json.getString("someString");
    } catch (JSONException e) {
        Log.d(TAG, "Failed to load from JSON: " + e.getMessage());
    }


You can use the org.json package, bundled in the SDK.

See here: http://developer.android.com/reference/org/json/JSONTokener.html


One more choice: use Jackson.

Simple usage; if you have a POJO to bind to:

  ObjectMapper mapper = new ObjectMapper(); // reusable
  MyClass value = mapper.readValue(source, MyClass.class); // source can be String, File, InputStream
  // back to JSON:
  String jsonString = mapper.writeValue(value);

to a Map:

  Map<?,?> map = mapper.readValue(source, Map.class);

or to a Tree: (similar to what default Android org.json package provides)

  JsonNode treeRoot = mapper.readTree(source);

and more examples can be found at http://wiki.fasterxml.com/JacksonInFiveMinutes.

Benefits compared to other packages is that it is lightning fast; very flexible and versatile (POJOs, maps/lists, json trees, even streaming parser), and is actively developed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜