Json - how to parse a url in Android - android

I want to parse json from a url and use the json data with a listview.
I also want to only list the score and the name, but I have no idea how. Thanks.
{
"level":[
{
"id":1,
"server":[
{"score":33,"name":"Car"},
{"score":72,"name":"Bus"},
]
}
]
}

Do you know how to retrieve the data?
After you retrieve the data, parsing it is very simple. To get each individual item with its attributes I would use the following code:
String responseFromUrl;
JSONObject JSONResponse = new JSONObject(responseFromURL);
JSONArray level = JSONResponse.getJSONArray("level");
//The following loop goes through each object in "level". This is nessecary if there are multiple objects in "level".
for(int i=0; i<level.length(); i++){
JSONObject object = level.get(i);
int id = object.getInteger("id");
JSONArray server = object.getJSONArray("server");
//This second loop gets the score and name for each object in "server"
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.get(i);
int score = serverObject.getInteger("score");
String name = serverObject.getString("name");
}
}
Obviously replace "responseFromUrl" with the JSON response from the url in string format. If you don't know why I used JSONObject, JSONArray, String, Integer, etc., or are just confused about this, Udacity has a good course for making http connections and parsing JSON responses from APIs.
Link to Udacity Course

You can use the gson library to convert json to an java object
Download the latest jar and import into your project, currently you can download the latest at this link:
https://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.1/gson-2.8.1.jar
After, this will help you:
https://stackoverflow.com/a/23071080/4508758
Hugs!

Related

getJSONArray wrong format for {"GetProdByBizResult":{"TotalCount":4,"RootResults":[{....}]}}"

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");

Android how to change value of a Key/Value Pair inside JSONObject

Hi i want to change/alter value of a string inside a json object which inside a JSONArray and which is from a file stored in internal storage.
My initial thoughts are to convert the object to a string do a find a replace and convert back to JSONObject search the JSONArray for the JSONObject remove the old one and put the new one in. Then save the array as a .JSON File to internal storage (will this replace the file thats already there or will it create another file with the same name?).
This is my initial thoughts on how to do this but is this the correct way or is there easier more efficient way to do this?
First, you need to retrieve the required JSON Object form the JSON Array.
You can update the key-value pair of your JSON Object directly by using
mJsonObj.put("<key>", <value>).
try using this :
nameValuePairs.add(new BasicNameValuePair("cus_id", cus_id));
getting data in this:
JSONObject json = new JSONObject(responseString);
JSONArray jArray = json.getJSONArray("customer");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
cus_points = json_data.getString("cus_points");
Depends on the library you are using for parsing JSON. Some do allow code like jsonOArray.get("jsonObject").put("key", "val");
Some require to obtain the object first then do something like
JsonObj = jsonArray.get("jsonObject"); jsonObj.putVal("key", "val");
Which library do you use for processing json?

android how to parse json

public void HelloWord {
for (int i = 0; i < 20; i++) {
Log.d("Great");
}
}
The code above doesn't work why?
I try to get value name
Does anybody know where is the problem?
org.json.JSONException: Value ...Content of link... at
org.json.JSON.typeMismatch at org.json.JSONArray.
I prefer to use the GSON library, as it is a fast and effective JSON parser. Once added to the project you will need to create classes to represent the data returned. You then can call a single function to create your objects for you:
gson.fromJson();
An exceptionally good article on the use of GSON can be found at http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html - it even uses Twitter for the example.
I think that you are missing the way that JSON works. Anything in {} is an Object, while [] designates an array. So the root of the twitter feed is a JSONObject, NOT a JSONArray:
Try something more like this:
JSONObject obj = new JSONObject(mStringBuilder.toString());
JSONObject trends = obj.getJSONObject("trends");
JSONArray today = trends.getJSONArray("2012-04-10");
for (int i = 0; i < today.length(); i++) {
JSONObject tag = today.getJSONObject(i);
String name = tag.getString("name");
// do whatever with name
}
Much easier, and its clearer how it works. JSONObjects are dictionaries, with a simple mapping between keys and values - each Object ({}) can contain either more objects, or arrays ([]) which can contain either simple integers or more objects

How to parse this JSON object

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

Trouble with Android JSONObject from Grails webservice

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:

Categories

Resources