简体   繁体   中英

Parsing JSON into a string array or xml

I am trying to connect to a server which than connect to Google Places API and returns me my required data, the data that is being returned is in this format Here

Now in my Android Application i have this as a string or string[] , issue is how can i now parse it as an XML or convert it to a native type like a List or something so i can than use it?

If you look at the returned string the actually array results starts after the two elemenets html_attributions & next_page_token so how can i seperate these and parse. Please help.

I would recommend you using the Gson library from Google, it can easily convert JSON -> Object . Here is a nice tutorial for you : tutorial . This library is used by famous library Retrofit which is made for these calls and it will download the data and convert it to object using Gson : retrofit

There are a variety of ways to perform Json parsing in android.

If you only want to take the json and convert it to a java objects, then you can use gson. When serializing the object, gson will ignore any key in the json that doesn't match the java object that you are going to use for serialization. Therfore, just create your java object with the results instance variable,

https://code.google.com/p/google-gson/

You can use the built in JsonReader class to obtain the "results" and place that into a json array, if you want to single that out.

It is also good to become familiar with retrofit. This library provides a little more functionality than your solution needs however. This library abstracts the whole http request, response, json parsing and gson serializtion for you. So simply, you call a method on the object and get back the json in already serialized pojo.

http://square.github.io/retrofit/

If your returned data is in json format, create one JsonObject , Parse it as Json instead of xml , you can retrieve the value and create String[] . Take help from this tutorial

Of-course you can use Gson library to serialize and de-serialize jsonObject to pojoObject .

Ideally you should use a cool convenient library like Google GSON as mentioned by others for JSON parsing, but I'll explain how to use your json string with the old simple org.json library anyway. If your json string returned from server is in a string s, do:

    JSONObject places=new JSONObject(s);
    JSONArray results=places.getJSONArray("results");
    for(int i=0;i<results.length();i++){
       System.out.println(results.getJSONObject(i).getString("place_id"))
       System.out.println(results.getJSONObject(i).getString("scope"));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM