Android - how to format objects in JSON - android

I have this class:
class Type{
public int id;
public String name;
}
and I want to format object in JSON this way
{[1,"superMarket"],[2,"restaurant "]}
and also put data from JSON to "Type" object
can some one help me please......

You can get an easy to understand example for encoding and parsing json:
Android JSON Tutorial: Create and Parse JSON data
and
JSON in Android - Tutorial

you nee to use a jasonArray and thee jsonObject ro do this..
you can viw this answer
Android create a JSON array of JSON Objects

Type to JSON
JSONObject jsonObj = new JSONObject();
jsonObj.putString("id", id);
jsonObj.putString("name", name);
You can add as many jsonObjs to JSONArray.
JSON to Type
Type type = new Type();
type.setId(jsonObj.optString("id"));
type.setName(jsonObj.optString("name"));

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

How to send list of byte arrays to json

How i can pass ArrayList<byte[]> to JSONObject as a parameter?
For example, I need to send a Id (string), Name (string) and photoList (ArrayList<byte[]>) in a json object.
You can use GSON LIBRARY . The code you need can be as :
String jso;
jso = new Gson().toJson(photoList);
It should convert the arraylist(i.e. photoList) to jsonObject.
Just use GSONlib for this if you want to convert arraylist into json
If you are using GSON library use the following code to convert your ArrayList to JSON.
String jsonString = new Gson().toJson(yourArrayList);

How to extract objects from json

I have a scenario where I need only 1 objects out of the entire json.
{"id":"1","first_name":"Steve","last_name":"Holt","user_type":"Teacher","user_key_area":"Math"}
In above I want to extract user_type.
How will I do?
You can use Google GSON to parse the json response and map it to the model directly . Here is the tutorial for the same TUTORIAL
Use this to extract the user_type from the json, pass the your json response in place of response variable.
JsonObject object =new JsonObject(response);
String user_type = object.getString("user_type");
You are getting this json in response you can get 1 object like this:
String value = response.getString("Key Name");
Get Response and that create JsonObject
JsonObject jsonObject =new JsonObject(res);
Create String object and pass string parameter "user_type"
String userType = jsonObject.getString("user_type");

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