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.
Related
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();
}
I have a trouble finding a way how to parse this JSON.
{
"token":"3c7dbdc69c02eb365b2900d3e5027a08c79fce43",
"profiles":["User","PartnerUser"],
"status":"OK"
}
Plz,i need your hepl. I find atrouble with this "profiles":["User","PartnerUser"]
create a class that represent that json file and then parse it via GSon library:
Possible scenario:
Result.class
public class Result{
String token;
List<String> profiles;
String status;
//getter and setter
}
to parse json:
Gson gson = new Gson();
Result result = gson.fromJson(json, Result.class);
ArrayList<String> profiles = new ArrayList();
profiles = result.getProfiles();
check this
Are you using some library to perform JSON parsing?
If not, you can use the getJSONArray(..) method passing "profiles" as name of the array
I have JSON data to parse. The structure is not fixed, and sometimes it comes as a single string and other times as an array.
Currently, we are using the GSON library for parsing JSON, but are facing problems when it comes as an array.
For example:
1. {"msg":"data","c":300,"stat":"k"}
2. {
"msg": [
" {\"id\":2,\"to\":\"83662\",\"from\":\"199878\",\"msg\":\"llll\",\"c\":200,\"ts\":1394536776}"
],
"c": 200,
"stat": "k",
"_ts": 1394536776
}
In the example above, sometimes I get msg as a string and sometimes as an array.
Can anyone help me? If I decide to use JSON parsing, it will be very tedious because I have around 20+ API to parse and each API contains a mininum of 50 fields.
You can use JSONObject and JSONArray classes instead of GSON to work with JSON data
for the first example
String jsonStr = "{\"msg\":\"data\",\"c\":300,\"stat\":\"k\"}";
JSONObject jsonObj = new JSONObject(jsonStr);
String msg = jsonObj.getString("msg");
Integer c = jsonObj.getInteger("c");
String stat = jsonObj.getString("stat");
For the second example
String jsonStr = ... // "your JSON data";
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonArr = jsonObj.getJSONArray("msg");
JSONObject arrItem = jsonArr.getJSONObject(0);
//and so on
Also JSONObject class have method opString, opArray which does not throw exception if data you trying to get is not exist or have a wrong type
For example
JSONArray arr = jsonObj.optJSONArray("msg");
JSONObject msg = null;
if (arr != null) {
msg = arr.getJSONObject(0)
} else {
msg = jsonObj.getJSONObject("msg");
}
You can use Google GSON lib for directly parse the json to class object. This is easy and accurate.Okay do one thing both time code is different, if the code is 300 directly parse the json object without GSON. if the code is 200 the use the GSON (Define the similar java class)
String c= json.getString("c");
if(c.equals("300")
String message = status.getString("msg");
There are two ways to parce JSON.
Manually using Android OS JSON Parser Android JSON Parsing And Conversion
Using GSON Library [Library] (https://code.google.com/p/google-gson/downloads/list). This easy to handle if you know all the parameters and models of json response.
Refer the code snippet below to deserialize your json using Google's Gson library without exceptions.
String jsonStr = "your json string ";
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
JsonElement elem = jsonObj.get("msg");
if(elem.isJsonArray()) { //**Array**
ArrayList<MyMessage> msgList = gson.fromJson(elem.toString(), new TypeToken<List<MyMessage>>(){}.getType());
} else if(elem.isJsonObject()) { //**Object**
Note note = gson.fromJson(elem.toString(), MyMessage.class);
} else { //**String**
String note = elem.toString();
}
MyMessage class
public class MyMessage {
String to;
String from;
String msg;
int id;
int c;
long ts;
// Setters and Getters
}
I have an array of classes of this type:
public class IndexVO {
public int myIndex;
public String result;
}
And this is my array:
IndexVo[] myArray = { indexvo1, indexvo2 };
I want to convert this array to json, any idea how?
This wouldn't be as easy as JSONArray mJSONArray = new JSONArray(Arrays.asList(myArray)) since your array contains objects of unsupported class. Hence you will have to make a little more effort:
JSONArray mJSONArray = new JSONArray();
for (int i = 0; i < myArray.length; i++)
mJSONArray.put(myArray[i].toJSON());
And add toJSON() method to your IndexVo class:
public JSONObject toJSON() {
JSONObject json = new JSONObject();
...
//here you put necessary data to json object
...
return json;
}
However, if you need to generate JSON for more than one class, then consider libraries which do it automatically, flexjson, for example.
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();
}