parsing JSON using GSON that has arrays - android

I've used GSON to retrieve a simple piece of JSON that didn't include arrays, and I placed them into a list of objects:
Type listType = new TypeToken<List<SingleEvent>>(){}.getType();
List<SingleEvent> events = new Gson().fromJson(jsonResponse, listType);
SingleEvent is the class I created and just included simple string variables.
Now, I want to create an object that can take Arrays from JSON strings.
[{"ticketmaster":"http:\/\/www.ticketmaster.ca","images":["http:\/\/www.example.com\/sites\/default\/files\/imagecache\/gallery\/SNW_4.jpg","http:\/\/www.example.com\/sites\/default\/files\/imagecache\/gallery\/AB.jpg","http:\/\/www.example.com\/sites\/default\/files\/imagecache\/gallery\/L5Y.jpg","http:\/\/www.example.com\/sites\/default\/files\/imagecache\/gallery\/TOS.jpg"]}]
So, in my object that will hold this data I just made a variable like this:
private ArrayList images;
I get a warning, but I'm sure how to handle incoming json arrays.

But what if you can parse the same JSON response using native classes?
Here is a simple try:
try {
JSONObject obj = new JSONObject("Your JSON String");
JSONArray array = obj.getJSONArray("images");
for(int i=0; i<array.length(); i++)
{
System.out.println("=====> Image at index "+i+"==>"+array.getString(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

populating arraylist of arraylist

I have an arraylist of arraylist which I am tring to populate but its not working.The response is being fetched from server.the response comes as follows
[{"QKey":"1234","OptionLabel":"Ground Floor","optionValue":"0"},{"QKey":"5678","OptionLabel":"1st Floor","optionValue":"1"}
I am trying to fetch it,add it in arraylist and populate but it seems to be not working
this is my code
String dropDownResponse=readFromFile(2);
Log.d("Reading from file",dropDownResponse);
JSONArray jsonArray = new JSONArray(dropDownResponse);
formModel.setName(rowLabel);
formModel.setIsMandatory(isMandatory);
formModel.setInputType(inputType);
/* formModel.setName("SAMPLE LABEL");
formModel.setIsMandatory("Y");
formModel.setInputType("selectbox");*/
spinnerList.add(formModel);
spinnerPopulationList.get(spinnerList.size()-1).set(0,rowLabel);
for(int j=0;j<jsonArray.length();j++)
{
JSONObject jsonObject = jsonArray.getJSONObject(j);
spinnerRowId=jsonObject.getString("QKey");
Log.d("QKey",spinnerRowId);
optionLabel=jsonObject.getString("OptionLabel");
Log.d("Option Label",optionLabel);
if(rowId.equals(spinnerRowId))
{
spinnerPopulationList.get(spinnerList.size()-1).set(spinnerPopulationList.get(spinnerList.size()-1).size()-1,optionLabel);
}
}
for(int h=0;h<spinnerPopulationList.get(spinnerList.size()-1).size();h++)
{
Log.d("spinner item"+rowLabel+"["+h+"]",spinnerPopulationList.get(spinnerList.size()-1).get(h));
}
this line in the code shows indexOutOfBoundException
if(rowId.equals(spinnerRowId))
{
spinnerPopulationList.get(spinnerList.size()-1).set(spinnerPopulationList.get(spinnerList.size()-1).size()-1,optionLabel);
}
I don't think you need a two dimensional AllayList to accomodate this json. This is just an array of objects. You can use Gson to parse it quite easily.
You will need a couple of response classes like
class ResponseObj {
private String Qkey;
private String OptionLabel;
private String optionValue;
//Constructor(s), getters and setters
}
class Response {
private ArrayList<ResponseObj> objects = new ArrayList<>();
//Constructor(s), getters and setters
}
Then you can use Gson to parse the json and make an object out of it. You can use something like this where you are getting the response from server.
Response response = gson.fromJson(YOUR_JSON, Response.class);
for(ResponseObj object : response.getObjects()) {
//In this loop, you are iterating over each object in your json
//which looks like
//{"QKey":"1234","OptionLabel":"Ground Floor","optionValue":"0"}
doSomething(object);
doSomethingWithKey(object.getQKey());
}
Here is how you can use Gson in your project.

How to get JSON Object in another one in android

I have the following JSON and I want to get "temp" and "pressure" in "main" key,
but I don't know how to do that.
this is my JSON :
JSONObject mainJsonObject = yourJsonObject.getJSONObject("main");
float pressure = mainJsonObject.getFloat("pressure");
float tempMin = mainJsonObject.getFloat("temp_min");
float tempMax = mainJsonObject.getFloat("temp_max");
String jsonString = ... //Your json string
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject mainObject = jsonObject.getJSONObject("main");
double temp = mainObject.getDouble("temp");
//And get other fields just like the line above.
You can also use Gson library which makes parsing jsons super easy.
First define your model according to your json:
public class JSON {
public Main main;
//...
public static class Main {
public double temp;
public int pressure;
//...
}
}
Then parse the json string using Gson:
JSON object = new Gson().fromJson(jsonString, JSON.class);
double temp = object.main.temp;
First copy your json model to the JsonUtils to generate your models(classes), Then you can easily use Gson to parse your json and deserialize it in to your classes.
For example you can see this Gson Tutorial
You need to get root JSON object, and then get your nested "main" object.
It would be better if you provide your JSON file. But having tree structure, the code should look somehow like this:
//Doing it inside try/catch block, because it may throw JSONException
try{
//Getting root JSON object
JSONObject rootJSON = new JSONObject(s);
//Getting nested "main" object from root object
JSONObject mainJSON = rootJSON.getJSONObject("main");
//Getting custom String from JSON object, say "temp"
String ourString = ourObject.getString("temp");
//Then you can use it whatever way you want
Log.e("JSONObject", ourString);
//Handling JSONException
} catch(JSONException e) {
e.printStackTrace();
}

How to set color to json array in mainactivity java using if condition

I have a json file [{name:dd,sname:f,add:xzxx},{name:dd,sname:f,add:xzxx},{name:dd,sname:f,add:xzxx},{name:dd,sname:t,add:xzxx},{name:dd,sname:t,add:xzxx},name:dd,sname:t,add:xzxx}..and so on.
I want to display the output in android such that if sname:f then the lsitview color should be red else any color
Any help..
My output has 3 columns Name,SName,Add which displays the json in listview which displays the json data.I want an if loop for the json array "sname"
Try this,
try {
JSONObject json = new JSONObject(content);
JSONArray leaders= json.getJSONArray("rows");
Log.d("leaders",leaders.toString());
for(int i=0;i<leaders.length(); i++){
JSONObject jsonas = leaders.JSONObject(i);
String fname = jsonas.getString("Fname");
Log.d("First Names",fname);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Just replace your key names and it works.
Parse the JSON array and store it in an ArrayList.
Pass the ArrayList to your custom adapter.
Toggle the view in the getview method of your adapter.

how to get data from nested json which is not having name in android?

i have a JSON like below.
this is sample json.. i have my json structure like this. if this json has any error please ignore that.
[
[
"{"category_id":1,"category_name":"1Appetizers","image_id":0}",
"{"category_id":13,"category_name":"Buffet","image_id":0}"
],
[
"{"subcategory_id":1,"category_id":12,"subcategory_name":"Beer","image_id":0}",
"{"subcategory_id":2,"category_id":12,"subcategory_name":"Wine","image_id":0}"
],
[
"{"menucategory_id":1,"menucategory_id":12,"menucategory_name":"dosa","image_id":0}",
"{"menucategory_id":2,"menucategory_id":12,"menucategory_name":"idly","image_id":0}"
]
]
how do i parse this JSON in android. i want to show category_name in one page and other details in some other page. there is no name for object.
Like the other commenters have mentioned this is not real JSON.
But here is an attempt to answer your question anyway.
I would create objects that represents the data you want to serialize and deserialize to and form JSON. It looks like you would have objects Category, Subcategory, and MenuCategory. Then you would probably have another object that holds lists of those three objects.
Then I would use GSON to serialize and deserialize your object. Let it do the heavy lifting for you.
try the following code. it might help you
// say you have your json in a String named jsonString
try
{
JSONArray array = new JSONArray(jsonString);
JSONArray firstJsonArray = array.getJSONArray(0);
JSONArray secondJsonArray = array.getJSONArray(1);
JSONArray thirdJsonArray = array.getJSONArray(2);
for (int i = 0; i < 2; i++)
{
JSONObject firstJsonObject = firstJsonArray.getJSONObject(i);
JSONObject secondJsonObject = secondJsonArray.getJSONObject(i);
JSONObject thirdJsonObject = thirdJsonArray.getJSONObject(i);
String categoryName = firstJsonObject.getString("category_name");
String subcategoryName = secondJsonObject.getString("subcategory_name");
String menucategoryName = thirdJsonObject.getString("menucategory_name");
// Now here you can use these values to do anything
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

Parse JSON String array for individual strings/ints

I am getting information from a MySql DB via PHP. The information is returned in the following JSON array:
06-15 15:20:17.400: E/JSON(9865): {"tag":"get_game_state","success":1,"error":0,"GameState":{"monster":"Troll","qty":"1","exp":"0"}}
The json is parsed and string is built using StringBuilder. Now that I have the information returned I want to parse it for the individual strings/ints it contains to put them in a local sqlite db.
Here are the two lines in question
userFunctions.getServerGameState(email, monster, qty, exp); //this line gets the JSON array and the above information is returned
db.saveLocalGameSate(monster, qty, exp); //this line should take that information take String monster int exp and int qty and put them in the local db.
How should I convert that returned information into an individual string and ints so that they can be used in the next line of code? Any direction to some resources would be very helpful.
update
I have added the following lines inbetween the two above lines of code, output is a null pointer exception
try {
JSONArray arr = new JSONArray(GameState);
JSONObject jObj = arr.getJSONObject(0);
String virtumon = jObj.getString("monster");
Integer qty = jObj.getInt("qty");
Integer exp = jObj.getInt("exp");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
That's not actually a JSON array; it's a JSON object (cause of the curly braces instead of square brackets.)
One of the constructors to JSONObject() accepts a string containing JSON and will parse it and create a JSON object. I can't post links yet but see the JSONObject docs at d.android.com.
Once you have a JSONObject you can use getString(), getInt(), optString() and optInt() to pull out the data you need.
Assuming 'responseString' is the full response string:
try {
JSONObject responseObj = new JSONObject(responseString);
JSONObject gameStateObj = responseObj.getJSONObject("GameState");
String monsterType = gameStateObj.getString("monster");
int qty = Integer.parseInt(gameStateObj.getString("qty"));
int exp = Integer.parseInt(gameStateObj.getString("exp");
} catch (JSONException ex) {
e.printStackTrace();
}
"qty" and "exp" are strings in your json so you need to getString then convert to int. I think this code is correct; haven't tested it.

Categories

Resources