How do I parse a JSON feed in Android?
相关问题
- Jackson Deserialization not calling deserialize on
- How can I create this custom Bottom Navigation on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Bottom Navigation View gets Shrink Down
Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.
Get your JSON:
Assume you have a json string
Create a JSONObject:
If your json string is an array, e.g.:
then you should use
JSONArray
as demonstrated below and notJSONObject
To get a specific string
To get a specific boolean
To get a specific integer
To get a specific long
To get a specific double
To get a specific JSONArray:
To get the items from the array
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a
JSONObject
for detail extraction:Once you have your
JSONObject
refer to the SDK for details on how to extract the data you require.Writing JSON Parser Class
Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.
2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.
2.2. Use parser class to get
JSONObject
and looping through each json item. Below i am creating an instance ofJSONParser
class and using for loop i am looping through each json item and finally storing each json data in variable.