{
"id": "1",
"name": "test1",
"data_city": "a:35: {i:22;s:6:\"61,800\";i:23;s:6:\"61,800\";i:24;s:6:\"61,800\";i:25;s:6:\"61,800\" ;i:26;s:6:\"61,800\";i:27;s:6:\"61,800\";i:28;s:6:\"61,800\";i:29;s:6:\"61,800\";i:30;s:6:\"61,800\";i:31;s:6:\"61,800\";i:54;s:6:\"61,800\";i:16;s:6:\"61,800\";i:32;s:6:\"61,800\";i:52;s:6:\"61,800\";i:21;s:6:\"61,800\";i:33;s:6:\"61,800\";i:37;s:6:\"61,800\";i:34;s:6:\"61,800\";i:36;s:6:\"61,800\";i:38;s:6:\"61,800\";i:41;s:6:\"61,800\";i:35;s:6:\"61,800\";i:39;s:6:\"61,800\";i:40;s:6:\"61,800\";i:42;s:6:\"61,800\";i:44;s:6:\"61,800\";i:43;s:6:\"61,800\";i:46;s:6:\"61,800\";i:45;s:6:\"61,800\";i:47;s:6:\"61,800\";i:49;s:6:\"61,800\";i:53;s:6:\"61,800\";i:50;s:6:\"61,800\";i:48;s:6:\"61,800\";i:51;s:6:\"61,800\";}"
}
This is my json response
i need to get data from string data_city
First of all, your JSON is not valid - probably a copy paste error.
Anyway, there are several ways to do this. One option is to use the built in JSONObject type:
String jsonString = "YOUR_JSON_STRING";
JSONObject objJSON = new JSONObject(jsonString);
String dataCity = objJSON.getString("data_city");
Hope this helps. Be sure to run your JSON String through a validation tool first. This one works nicely: https://jsonformatter.curiousconcept.com/
Related
I successfully get data from wcf web service in my android studio app.
I get this format for the json response.
{"GetProdByBizResult":{"TotalCount":4,"RootResults":[{"catId":1348,"catOrder":1,...
what is the parameter that has to be provide in order to convert it to JSONArray ?
JSONArray jsonArray = jsonResponse.getJSONArray("RootResults");//this doesn't work
I found a workaround by replacing my json string to "RootResults":[{"....}]}"
then
jsonResponse.getJSONArray("RootResults");
is working perfect
{
"GetProdByBizResult": {
"TotalCount": 4,
"RootResults": [
{
"catId": 1348,
"catOrder": 1
}
]
}
}
Json array "RootResults" is a part of json object "GetProdByBizResult" so we need to take "GetProdByBizResult" josn object first and then from this object you can fetch the "RootResults" json array, like
JSONObject jsonObject = jsonResponse.getJSONObject("GetProdByBizResult");
JSONArray jsonArray = jsonObject.getJSONArray("RootResults");
I want to get a list of friends' names from the Facebook API in Android. In that process, I want to learn how to read JSON objects/Arrays.
I have JSONObject and/or JSONArrays that have been passed to me. I don't know what's in them*. I know how to read the data once I know what fields exist, but I can't read anything as far as I can tell, without a key. Even with the key, How can I tell what's in it?
Basically, I'd like a piece of code that looks like:
JSONArray mArray = response.getJSONArray();
String theEntireDatabase = mArray.getStringOFEntireDatabase();
and have it respond with a String that looks like this:
{
"phoneNumber": [
{
"type": "work",
"num": "11111"
},
{
"type": "home",
"num": "2222"
}
],
"address": {
"state": "World",
"address": "infinite space, 000",
"city": "Android city"
},
"surname": "Swa",
"name": "Android"
}
Having known nothing of what is in the database beforehand?
*it could be "color:" it could be "nuclear threat level:" for all I know.
I tried this, but it only gives keys: Javascript get JSON key Name
JSONArray mArray = response.getJSONArray();
String theEntireDatabase = mArray.toString();
This should work well.
If you want the JSONArray pretty printed you can add this after the code I've just provided you.
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(theEntireDatabase);
String prettyJsonString = gson.toJson(je);
JSONObject#keys will tell you what keys are defined for the object. JSONArray#length will tell you how many entries are in the array (and therefore the range of values you can use for index with the other methods: 0 through length() - 1). JSONObject#toString/JSONArray#toString will give you the string you've asked for.
Take a look at Jacksons built-in tree model feature.
http://wiki.fasterxml.com/JacksonTreeModel
And your code will be:
public void parse(String json) {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
JsonNode rootNode = mapper.readTree(json);
Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields();
while (fieldsIterator.hasNext()) {
Map.Entry<String,JsonNode> field = fieldsIterator.next();
System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
}
}
besides the technical answers (JSONObject#toString(n) seems the easiest - see http://developer.android.com/reference/org/json/JSONObject.html),
I would often use two more pragmatic solutions:
look for an API documentation... I know, it sounds crazy, but some companies do offer such a thing
hack together a short javascript script to try the API and inspect the result in the developer console/firebug/whatever is handy
Example JSON Page
http://maps.googleapis.com/maps/api/geocode/json?latlng=51.155455,-0.165058&sensor=true
#SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
// This works and returns address
JSONArray resultArry = reader.getJSONArray("results");
String Address = resultArry.getJSONObject(1).getString("formatted_address").toString();
Log.e("Address", Address);
// Trying to get PostCode on code below - this is not working (log says no value at address components)
JSONArray postCodeArray = reader.getJSONArray("address_components");
String postCode = postCodeArray.getJSONObject(1).getString("long_name").toString();
Log.e("PostCode", postCode );
This code returns the address correctly. How can I get the post code long_name which is inside address_components?
Solution
I had to get each array, and then get the post code value.
I am using the value 7, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.
reader.getJSONObject(1).getJSONArray("address_components");
Your problem is that results is a JSONArray that contains a child JSONObject composed of several children: "address_components", "formatted_address", "geometry", and "types". The result array actually contains many of these such objects, but let's focus on just the first child for now.
Look carefully at your code. With this line:
JSONArray resultArry = reader.getJSONArray("results");
You are getting the entire results. Later on, you then call the same method again:
JSONArray postCodeArray = reader.getJSONArray("address_components");
But you're asking for an "address_components" from the reader, where I do not expect you'll find anything (having already read the entire result before.) You should instead be working with the JSONArray you already got before, since it already contains the entire result.
Try something like:
JSONObject addressComponents = resultArry.getJSONObject(1).getJSONObject("address_components");
String postCode = addressComponents.getString("long_name");
Note: I don't know why you're singling out JSONObject #1 (as opposed to 0, which is the first, or any other one of them) and I also am not sure why you named the String postCode. So if I've misunderstood your intention, I apologize.
Is difficult to find the error... because all looks well. The problem maybe can exist when you make the json.put("address_components", something);
So my advice is put a breakpoint at this line
JSONArray postCodeArray = reader.getJSONArray("address_components");
o display the json in logcat
Log.d("Simple", reader.toString());
Then Paste your json in this web page to view more pretty
http://jsonviewer.stack.hu/
and check if all keys are stored well.
Solution
Need to get each array, and then get the post code value. The value 7 is used, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.
This is the json response from my server . How can i parse it and store it in HashMap? Please help me.
{'records':
[{
'number':165,
'description': 'abcd'
},
{
'number':166,
'description': 'ab'
},
{
'number':167,
'description': 'abc'
}]
}
im new in android but maybe you can do something like this:
JSONObject JsonObject = new JSONObject(json);
JSONArray JsonArray_ = JsonObject .getJSONArray("records");
for (int i = 0; i < numberOfItems; i++) {
JSONObject record= JsonArray_photo.getJSONObject(i);
parsedObject.number = record.getString("number"); //its the same for all fields
map.add(parsedObject);
}
I done something like that for my own JSON parser. hope this helps. cheers
I suggest you look at the gson library, which makes it very easy indeed to parse JSON into an object representing the data. So you could create a Record object, with public member variables for number, description, and then use gson to parse the JSON into an object array.
http://code.google.com/p/google-gson/
Add the .jar to your libs folder and then use it like this:
Record[] records = new GsonBuilder().create().fromJson(jsonString,Record[].class)
int number = record[0].number;
The org.json package is included in Android: http://developer.android.com/reference/org/json/package-summary.html
Use is simple:
JSONObject json_object = new JSONObject(String json_string);
Each property can then be accessed as a Java property, e.g. json_object.property. It will throw a JSONException if the parsing fails for some reason (i.e., invalid JSON).
You can use Gson library, you can find full tutorial on softwarepassion.com
Okay I am quering data from a Grails webservice that returns JSON. The JSON when viewed with the JSONViewer app parses fine. When I take that same string and use JSONObject(string) in my Android app I get "value of String cannot be converted to JSONObject."
Here's my JSON string
[[{"class":"mygrails.TopTen","id":491,"ttAmount":14200000,"ttMlId":402,"ttRank":1,"ttWeekId":1108},{"class":"mygrails.MovieList","id":402,"mlApproved":1,"mlApprovedId":5,"mlMovieId":"GNOMEOAN","mlReleaseDate":"2011-03-08T07:41:45Z","mlTitle":"Gnomeo and Juliet","mlWeekId":1106}]]
Now the JSON is comes from the standard JSON conversion of a SQL data using render from the groovy file through the import grails.converters.JSON.
... //(call to render JSON in the groovy file)
def a
a = Table.findAll("from someTable as st where st.id=" params.id)
render a as JSON
...
So I am not sure what I doing wrong and why the JSON looks a little off to me. (still new to JSON)
In json if you see "[]" means its a json array and if you see "{}" it is an json object. Both of then can have the other nested inside then.
In your case the string the starts with json array.
So try something like the following
String str = "[[{"class":"mygrails.TopTen","id":491,"ttAmount":14200000,"ttMlId":402,"ttRank":1,"ttWeekId":1108},{"class":"mygrails.MovieList","id":402,"mlApproved":1,"mlApprovedId":5,"mlMovieId":"GNOMEOAN","mlReleaseDate":"2011-03-08T07:41:45Z","mlTitle":"Gnomeo and Juliet","mlWeekId":1106}]]";
JSONArray jsonArray = new JSONArray(str);
jsonArray = jsonArray.getJSONArray(0);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String class = jsonObject.getString("class"); // class will value "mygrails.TopTen"
Try to create an JSONArray from the String instead of JSONObject. I didn't test this but that should do the trick: you have two nested arrays that contain then actual data.
Check out your JSON online with http://jsonformat.com/
http://www.freeformatter.com/json-formatter.html
JSON Viewer
http://jsonviewer.stack.hu/
Paste your text in there and you can see what you should parse: