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");
Related
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!
I have a JSON as below
{
"shippingGroupListJson":[
{
"lineId":123,
"shippedTo":{
"country":"US"
},
"cartons":1,
"group":"4",
"shipInscription":{
"municipalInscription":"",
"inscriptionType":"",
"stateInscription":"",
"suframaInscriptionNumber":"",
"inscriptionBranch":"",
"contributorClass":"",
"inscriptionDigit":"",
"inscriptionNumber":""
},
"shipCartonDetails":[
],
"shippedContact":{
"firstName":"Mjjkk",
"email":"nob#gmail.com",
"fax":"--",
"phone":"80-121",
"lastName":"Henry"
},
"mobilityShipStatus":"Not Yet Shipped",
"shipDate":"13 Dec 2014"
},
{
"lineId":0,
"shippedTo":[
],
"cartons":0,
"group":"5",
"shipInscription":[
],
"shipCartonDetails":[
],
"shippedContact":[
],
"mobilityShipStatus":"",
"shipDate":"",
"shipStatus":""
}
]
}
If you see in this above JSON in key "shippedTo", when there is value , I get a JSON Object and when no value is present then i get a Blank JSONArray.
I need to fix this issue. I cannot communicate with the service team to change this as they won't make changes to it. Can any one tell me how can i do the required changes.
I know this is not the rite way, but i need to do something..
I tried using String.replaceAll(oldChar,newChar);
You say you are using GSON, in which case JsonArray and JsonObject are both subclasses of JsonElement.
But you do not say if you are using the DOM or Streaming technique with GSON.
You should show your parsing code, or the class that's being automatically used for the parsing.
In the meantime, based on what you have said, I would define my shippedTo field in my class as an Object. That should parse correctly (if using DOM), and after that you can analyse exactly what you have in that field.
Instead of:
private MyCountryType shippedTo;
Have:
private Object shippedTo;
You could simply check its type at runtime i.e
JSONObject jsPar=new JSONObject(json_data);
JSONArray jsarrPar=js.getJSONArray("shippingGroupListJson");
for(int i=0;i<jsarrPar.size();i++){
JSONObject js= jsarrPar.getJSONObject(i);
if(js.get("shippedTo") instanceof JSONArray){
//Treat it as an array
}
else{
//Treat it as a single json object
}
}
Furthermore if you need it as an JSONObject immaterial of it being a single element then do this to get your customized string
JSONObject jsPar=new JSONObject(json_data);
JSONArray jsarrPar=js.getJSONArray("shippingGroupListJson");
for(int i=0;i<jsarrPar.size();i++){
JSONObject js= jsarrPar.getJSONObject(i);
JSONObject js=new JSONObject(json_data);
if(js.get("shippedTo") instanceof JSONArray){
js.put("shippedTo",new JSONObject()); //purge the original array with this new blank element
}
else{
//Do your normal stuff
}
}
String curmodstring=jsPar.toString();
Hope you get the general idea.
I'll keep it short. I want to obtain the string value from "token". But from what I can see there is a "data" array within my json object. How do I retrieve the array and, specifically, the token string from this array?
{
"response":true,
"state":8,"data":{
"token":"$2a$08$oeH79FjMV6ZQTO.9qqfToujNBbst420Xx7o9jJdFgbJsJijtEpX\/O",
"numbers":[{
"number":"4581102282",
"enabled":"0",
"custid":"1528511113",
"route":"rock",
"clir":"2",
"mob":"1",
"clip":"",
"mbx":"0",
"trunk":"2",
"valid_from":"2011-09-07",
"valid_to":"2011-10-05"
}]
}
}
Simply use
JSONObject jsonObj=new JSONObject(response);
JSONObject jsonData=jsonObj.getJSONObject("data");
String token=jsonData.getString("token");
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: