Server Response (JSON Format) to Array Conversion - java

I am working on an android app in which i send an http response to a server and get a response in string which is in JSON format, now on the basis of this response i need to generate a stacked column chart using AChartEngine for different equipments. The response string looks like as follows
[{"ChartDate":null,"CycleStatus":null,"Cycle_Duration":0,"Cycle_Percent":0,"Duration":0,"EquipmentDescription":"MTConnect","EquipmentId":5,"EquipmentName":"MTC 1","EquipmentStatusColor":null,"EquipmentStatusDescription":null,"EquipmentStatusId":0,"EquipmentStatusIdentifier":null,"EquipmentStatusTypeId":0,"EquipmentStatusTypeName":null,"EquipmentStatusTypeName_resourceKey":null,"EquipmentTimeZoneId":null,"EventData":null,"GeneralStatusState":0,"IsFirstRowData":false,"Percentage":0,"ReportGroupId":0,"ReportGroupName":null,"ReportGroupValue":null,"StatusAction":0,"StatusDuration":[{"ChartDate":null,"CycleStatus":null,"Cycle_Duration":0,"Cycle_Percent":0,"Duration":561.60722222222023,"EquipmentDescription":"MTConnect","EquipmentId":5,"EquipmentName":"MTC 1","EquipmentStatusColor":"#008000","EquipmentStatusDescription":"In Cycle","EquipmentStatusId":0,"EquipmentStatusIdentifier":null,"EquipmentStatusTypeId":1,"EquipmentStatusTypeName":null,"EquipmentStatusTypeName_resourceKey":"EquipmentStatusTypeName.InCycle","EquipmentTimeZoneId":null,"EventData":null,"GeneralStatusState":0,"IsFirstRowData":false,"Percentage":0,"ReportGroupId":0,"ReportGroupName":null,"ReportGroupValue":null,"StatusAction":0,"StatusDuration":null,"TimeStamp":{"DateTime":"\/Date(-62135596800000)\/","OffsetMinutes":0},"UnknownDowntime_Duration":0,"UnknownDowntime_Percent":0},{"ChartDate":null,"CycleStatus":null,"Cycle_Duration":0,"Cycle_Percent":0,"Duration":134.57583333333525,"EquipmentDescription":"MTConnect","EquipmentId":5,"EquipmentName":"MTC 1","EquipmentStatusColor":"#FFFF00","EquipmentStatusDescription":"In Cycle","EquipmentStatusId":0,"EquipmentStatusIdentifier":"","EquipmentStatusTypeId":2,"EquipmentStatusTypeName":null,"EquipmentStatusTypeName_resourceKey":"EquipmentStatusTypeName.UnknownDowntime","EquipmentTimeZoneId":null,"EventData":null,"GeneralStatusState":0,"IsFirstRowData":false,"Percentage":0,"ReportGroupId":0,"ReportGroupName":null,"ReportGroupValue":null,"StatusAction":0,"StatusDuration":null,"TimeStamp":{"DateTime":"\/Date(-62135596800000)\/","OffsetMinutes":0},"UnknownDowntime_Duration":0,"UnknownDowntime_Percent":0}],"TimeStamp":{"DateTime":"\/Date(-62135596800000)\/","OffsetMinutes":0},"UnknownDowntime_Duration":0,"UnknownDowntime_Percent":0},{"ChartDate":null,"CycleStatus":null,"Cycle_Duration":0,"Cycle_Percent":0,"Duration":0,"EquipmentDescription":null,"EquipmentId":1,"EquipmentName":"PCS Loop 1","EquipmentStatusColor":null,"EquipmentStatusDescription":null,"EquipmentStatusId":0,"EquipmentStatusIdentifier":null,"EquipmentStatusTypeId":0,"EquipmentStatusTypeName":null,"EquipmentStatusTypeName_resourceKey":null,"EquipmentTimeZoneId":null,"EventData":null,"GeneralStatusState":0,"IsFirstRowData":false,"Percentage":0,"ReportGroupId":0,"ReportGroupName":null,"ReportGroupValue":null,"StatusAction":0,"StatusDuration":[{"ChartDate":null,"CycleStatus":null,"Cycle_Duration":0,"Cycle_Percent":0,"Duration":495.61333333332925,"EquipmentDescription":null,"EquipmentId":1,"EquipmentName":"PCS Loop 1","EquipmentStatusColor":"#008000","EquipmentStatusDescription":"In Cycle","EquipmentStatusId":0,"EquipmentStatusIdentifier":null,"EquipmentStatusTypeId":1,"EquipmentStatusTypeName":null,"EquipmentStatusTypeName_resourceKey":"EquipmentStatusTypeName.InCycle","EquipmentTimeZoneId":null,"EventData":null,"GeneralStatusState":0,"IsFirstRowData":false,"Percentage":0,"ReportGroupId":0,"ReportGroupName":null,"ReportGroupValue":null,"StatusAction":0,"StatusDuration":null,"TimeStamp":{"DateTime":"\/Date(-62135596800000)\/","OffsetMinutes":0},"UnknownDowntime_Duration":0,"UnknownDowntime_Percent":0},{"ChartDate":null,"CycleStatus":null,"Cycle_Duration":0,"Cycle_Percent":0,"Duration":200.56972222222623,"EquipmentDescription":null,"EquipmentId":1,"EquipmentName":"PCS Loop 1","EquipmentStatusColor":"#FFFF00","EquipmentStatusDescription":"In Cycle","EquipmentStatusId":0,"EquipmentStatusIdentifier":"","EquipmentStatusTypeId":2,"EquipmentStatusTypeName":null,"EquipmentStatusTypeName_resourceKey":"EquipmentStatusTypeNam
Now this is a response for five different equipments and how can i use this JSON string to an array so that i can extract the data of each equipment and send it to AChartEngine for drawing of chart?

You can convert the response string to JSONObject. The response you posted is JSONArray.
JSONArray jsonArray = new JSONArray(responseString);
int size = jsonArray.length();
ArrayList<JSONObject> arrayList = new ArrayList<JSONObject>();
for(int i= 0; i< size; i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
// use this jsonObject to get the value by passing the keys.
String value = jsonObject.optString(key);
//here is your array list of jsonobjects
arrayList.add(jsonObject);
}

Use below Code for Pass JsonArray and store Value into ArrayList.
JSONArray jArray = new JSONArray(mRes);
ArrayList<String> array1 = new ArrayList<String>();
for(int i= 0; i< size; i++) {
JSONObject jObject = jArray.getJSONObject(i);
String mValue = jObject.getString("your_json_object_name");
array1.add(mValue);
}

Use Gson api, it allows you to direct mapping of json objects to java objects. check following links for further reference:
http://code.google.com/p/google-gson/
https://sites.google.com/site/gson/gson-user-guide

Related

Json object to java arraylist

I have pass two values from ajax to my servlet.
I used
JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
and this is the output
{"0":"31/01/2017","1":"19/01/2017"}
Now I want to convert this data into a java arraylist but not really sure how.
I tried
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
JsonArray jsonArr = data.getAsJsonArray();
// jsonArr.
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i=0; i< jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
But got an error
java.lang.IllegalStateException: This is not a JSON Array.
Someone help me please? thanks.
Create instance of JsonArray then add json element to that array using key.
Here is your solution :
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
JsonArray jsonArr = new JsonArray();
for(Entry<String, JsonElement> entry : data.entrySet()) {
jsonArr.add(data.get(entry.getKey()));
}
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i = 0; i < jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
For a Json to be a valid JsonArray object you should have it to a proper format. Can you change your json string return from your ajax? If yes you should change it to something like this:
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson("{test: [{\"0\":\"31/01/2017\"},{\"1\":\"19/01/2017\"}]}", JsonObject.class);
System.out.println(data);
JsonArray jsonArr = data.getAsJsonArray("test");
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i=0; i< jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
If not you should parse it by your self and convert it to everything you want.

What should i use to store multiple images?

What should i use to store multiple images that i retrieve from for loop? array or list? Is there any example functions that i can use? Below is my example for loop where i get my data.
JSONObject mainObject = new JSONObject(response.toString());
JSONArray uniObject = mainObject.getJSONArray("result");
for(int i = 0; i < uniObject.length(); i++) {
JSONObject rowObject = uniObject.getJSONObject(i);
co.img1 = ipAddress +"img/store/" + rowObject.getString("store_banner");
}
Use ArrayList<>(); It's away more flexible than the normal array;

parse and get specific field from HTTP response in java

I try to parse a HTTP response to a JSONObject and retrieve some fields, coould be a String or int.
My response is a json array like this:
[{nid: "24161",changed: 1445936169,created: "1444728767",language: "en",status: 1,title: "bicycle",type: "product",uid: "2172",vid: "24161"}]
And I tried using:
JSONObject myObject = new JSONObject(response);
And gson , still after parsing the response turns to {}.
Thanks for any help.
You must use JSONArray instead of JSONObject
JSONArray array = new JSONArray(response);
You can then iterate throw the array and get the fields you want
for(int i=0; i<array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String nid = object.getString("nid");
int changed = object.getInt("changed");
//...
}
You are parsing json array into object. Use JSONArray instead of JSONObject
JSONArray myArray = new JSONArray(response);
you can get your object by index from your array.

How to decode in java a json representation of Google appengine Text

I have two appengine applications and am serving a string representation of a JSONObject from one and picking it up in the other. Every thing works well if I don't include a Text object in the JSON
Here is the specific part of the JSON object causing the trouble:
,\"text\":\u003cText: rthBlog 1\r\n\"If you don\u0027t learn from history you are doomed to repeat i...\u003e,
Here is how it looks like in string form:
< Text: rthBlog 1
"If you don't learn from history you are doomed to repeat i...>
Here are the relevant code placing the string in the data store [I am using json.simple]:
Text item_text = new Text("default text"); //it get filled by text longer than 500 char's
JSONObject j = new JSONObject();
j.put("text", item_text);
j.put("item_links", j_links);
item.setProperty("as_json", j.toJSONString());
datastore.put(item);
Here is the code retrieving it wrapping it in a JSONArray the array in a JSONobject and producing a String [I am using appengine json]:
JSONArray search_results = new JSONArray();
for(Entity e: items)
{
String j = (String) e.getProperty("as_json");
JSONObject jo;
if(j != null)
{
System.out.println(TAG + ".searchItems() string as json: " + j);
jo = new JSONObject();
jo.put("item", j);
search_results.add(jo);
}
}
JSONObject jo = new JSONObject();
jo.put("items", search_results);
return jo.toJSONString();
Here is the code picking it up [I am using appengine json]:
try
{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = (JSONArray) jsonObject.get("items");
JSONObject array_member = null;
JSONObject j;
for(int i=0; i<jsonArray.length(); i++)
{
array_member = jsonArray.getJSONObject(i);
System.out.println("array member" + array_member);
/*Text text = (Text)array_member.get("text"); //
System.out.println(text.getValue());*/
String s_item = array_member.getString("item");
System.out.println("item in string form: " + s_item);
j = new JSONObject(s_item); //This is the exception causing line
You need to be in control of your serialization and deserialization to and from JSON ...
meaning complex object are represented as simple text or numbers.
Here you are trying to serialize a complex object which is not what it is intended for. Make sure you serialize only the value the object is holding not the entire object.
A nice and very powerfull library enabling to fully take control of the serialization/deserialization process is Jackson.

Convert JSON array[array[String]] to Java array

I have a JavaScript JSON array[array[String]] called jsonArray in my JSP1.jsp.
I am converting jsonArray to a String jsonArrayStr using JSON.stringify(jsonArray) in JSP1.jsp.
I am passing jsonArrayStr as a parameter while calling another JSP JSP2.jsp this way-
"JSP2.do?jsonArrayStr="+jsonArrayStr
In JSP2.jsp, I am doing this-
String jsonArrayStr = request.getParameter("jsonArrayStr");
Now how do I convert jsonArrayStr to Java array (JSP2.jsp doesn't contain any JavaScript code)
Summary-
I have a JavaScript JSON Array in a JSP1.jsp, which I want to access as a normal Java array/arraylist in JSP2.jsp. How do I achieve this?
OK, so you have a two-dimensional array of strings represented as a JSON like this stored in a Java String:
[["a", "b", "c"],["x"],["y","z"]]
You need to somehow parse or "deserialize" that value into a Java String[][]. You can use a library like from http://www.json.org/java/index.html or http://jackson.codehaus.org/ or you can try to do it manually. Manually could be a little tricky but not impossible. The json.org library is very simple and might be good enough. The code would be something like this (I haven't tried/tested this):
JSONArray jsonArray = new JSONArray(jsonArrayStr); // JSONArray is from the json.org library
String[][] arrayOfArrays = new String[jsonArray.length()][];
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray innerJsonArray = (JSONArray) jsonArray.get(i);
String[] stringArray = new String[innerJsonArray.length()];
for (int j = 0; j < innerJsonArray.length(); j++) {
stringArray[j] = innerJsonArray.get(j);
}
arrayOfArrays[i] = stringArray;
}
somethingk like this
ArrayList<String> strings= new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
String[] Stringarray = strings.toArray(new String[strings.size()]);

Categories

Resources