问题
i have a Rest ful service,.. and i am getting a JSON data like,..
{
"returnCode": "success",
"RecievedData": {
"results": [
{
"details": [
{
"moredetails": [{
"id": "123456",
"price": "129.99",
"recorded_at": 3223322,
"lastrecorded_at": 0002020,
"seller": "google",
"availability": "Available",
"currency": "USD"
}],
"offers_count": 1,
"name": "google.com",
"recentoffers_count": 1,
"sid": "988008555566649",
"url": "http://google.com"
},
"moredetails"{
.
.
}
] details
{
{
[
]
}
"model": "abc",
"weight": "127",
"price_currency": "USD",
"features": {
.
'
}
"model": "abc",
"weight": "127",
"price_currency": "USD",
.
.
.
i am using this example or tutorial for this
and in that its calling json from this url
an dover there he is parsing data with this json object jsonarray = jsonobject.getJSONArray("worldpopulation");
so i am getting a data from a url as above how to parse this much of json data in that i want only 2 or 3 fields of json array,.
Please help ,.. with a example which is working,..for above,..
回答1:
You can use gson library. There is an example here!
回答2:
As it is nested json and You have not specified which fields do you need its difficult to answer so Use this class as a refrence class use method from where You need data to be displayed, It will return the first object of your array.
public class Parser {
public String getData() {
String content = null;
String result = "";
InputStream is = null;
// http get
try {
HttpClient httpclient = new DefaultHttpClient();
String webUrl = "your url";
HttpGet httppost = new HttpGet(webUrl);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.d("LOGTAG", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.d("LOGTAG", "Result :" + result);
} catch (Exception e) {
Log.d("LOGTAG", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jarray = new JSONArray(result);
JSONObject jobj = jarray.getJSONObject(jarray.getInt(0));
content = jobj.getString("key");//key=name of the field you require
} catch (Exception e) {
Log.d("LOGTAG", e.toString());
}
return content;
}
}
回答3:
I saw your comment ... you do not want to change your code. but parsing a json yourself is pretty slow in comparison to using Gson..and use of gson is so simple you just need to create simple pojo classes and it will convert whole json into java object which you can use anywhere. this is also a neat way of doing it.here is an example
来源:https://stackoverflow.com/questions/20516194/how-to-parse-huge-json-data-froma-url-or-restful-service-in-androidwithout-gson