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

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.

Related

Can't parse some JSON into a JsonArray using GSON

I am trying to get the values from a JSON response. I got everything to work, except extracting an array from the following string:
{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}
I know GSON is trying to parse it because I get this error:
Exception in thread "main" java.lang.IllegalStateException: Not a JSON Array: {"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}
I am using the following code to attempt to parse it:
final JsonElement midElement = obj.get("mid");
final JsonArray midArray = midElement.getAsJsonArray();
for(Object rate : midArray){
final JsonObject rateObj = (JsonObject)rate;
final JsonElement openElement = rateObj.get("o");
open = openElement.getAsFloat();
final JsonElement highElement = rateObj.get("h");
high = highElement.getAsFloat();
final JsonElement lowElement = rateObj.get("l");
low = lowElement.getAsFloat();
final JsonElement closeElement = rateObj.get("c");
close = closeElement.getAsFloat();
}
First of all it doesn't look like a valid JSON array. It should look like this
[{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}]
Try this following code to parse it in JSON format.
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("mid");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("o");
}
Then convert it your preferred data form.

How to acess the following property in this Json - JAVA

I have the following code that get the JSON in this URl :
https://www.googleapis.com/youtube/v3/search?key=AIzaSyCg3WitBUQl5ifC2QygQaZUPOSRMKfSD5E&channelId=UCPSDAF3Htm3AIxw4OUM3Lew&part=snippet,id&order=date&maxResults=20
I can acess the propierty "nextPageToken" and get your value with the following code:
JSONObject json = readJsonFromUrl(
"https://www.googleapis.com/youtube/v3/search?key=AIzaSyCg3WitBUQl5ifC2QygQaZUPOSRMKfSD5E&pageToken="
+ nextPageToken + "&channelId=" + new GetListAndPLayListYoutube().getIdUsuario()
+ "&part=snippet,id&order=date&maxResults=50");
System.out.println(json.get("nextPageToken"));
But i try Acess the property inside of "items" what is "videoId" and get the value of videoId, but not work, how can get the value of videoId
Try below code to get videoid from json String.
pass your json string object from parseJson() method:
private void parseJson(String responseString){
try {
Object object = new JSONTokener(responseString).nextValue();
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
Object object1 = jsonArray.getJSONObject(i);
if (object1 instanceof JSONObject) {
JSONObject jsonObject1 = (JSONObject) object1;
JSONObject jsonObject2= jsonObject1.optJSONObject("id");
String videoId = jsonObject2.optString("videoId");
System.out.println("videoId=" + videoId);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
It looks like you querying Youtube's Search API and extracting results from response. In which case, I would recommend using Google's API Client library (here) for Java instead of writing your own implementation.
Here are some examples of how to search Youtube using Google's API client and retrieve video information.

Retrieving a Json String using the correct library

I'm trying to get the content of msg which is ERROR. I'm doing that by transforming string return into an array.
Now the solution 1, works perfectly fine using import org.json.JSONArray;:
Vector<ClsReturn> ret = null;
ret = ds.ind(coll,uri );
JSONArray array = new JSONArray(" [{\"type\":1, \"txt\":\"ERROR\"}]");
int i = 0;
JSONObject myJsonObject = new JSONObject();
while(i < array.length()){
myJsonObject = array.getJSONObject(i);
System.out.println(myJsonObject.getString("txt"));
i++;
}
The above solution allows me tro retrieve the content of "txt", which is "ERROR".
However (below code) when I try to use the reutrn of String jsReturn = JSONArray.toJSONString(ret); I'm not capable to do that because the library I'm using doesn't support JSONArray.toJSONString, so I need to import org.json.simple.JSONArray; which in turn doesn't allow me to use array.getJSONObject(i) but both libraries org.json.simple.JSONArray and
org.json.JSONArray don't work together. Any workaround to get the desired outcome?
Vector<ClsReturn> ret = null;
ret = ds.ind(coll,uri );
String jsReturn = JSONArray.toJSONString(ret);//output(using simple.JSONArray) --> [{"type":1, "msg":"ERROR"}]
JSONArray array = new JSONArray(jsReturn);
int i = 0;
JSONObject myJsonObject = new JSONObject();
while(i < array.length()){
myJsonObject = array.getJSONObject(i);
System.out.println(myJsonObject.getString("txt"));
i++;
}
org.json.JSONArray has a toString() method that will output a JSON string. It also allows for indentation by using toString(int indent_factor)

Server Response (JSON Format) to Array Conversion

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

Android app to parse JSON from website

Ok, so the first hurdle was cleared in just a few minutes, let's see how this one does.
The code is pulling the JSON data from the website fine as I can see in my log, but now the JSONParser is failing. I think the issue is JSONObject versus JSONArray, but I can't figure that out.
Here is the data pulled from the JSON site as seen in the log:
09-10 09:45:00.175: I/log_tag(785): {"stoker":{"sensors":[{"id":"620000116F01CA30","name":"SS2","al":0,"ta":66,"th":75,"tl":65,"tc":66.3,"blower":null},09-10 09:45:00.175: I/log_tag(785): {"id":"E20000116F0CDB30","name":"brskt2","al":0,"ta":203,"th":32,"tl":32,"tc":70.6,"blower":null}],09-10 09:45:00.175: I/log_tag(785): "blowers":[{"id":"37000000119D8B05","name":"party","on":0}]}}
And here is the code trying to parse the data:
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Sensor resultRow = new Sensor();
resultRow.id = json_data.getString("id");
resultRow.name = json_data.getString("name");
resultRow.current = json_data.getString("tc");
resultRow.target = json_data.getString("ta");
arrayOfWebData.add(resultRow);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
And here is the entry in the log file when it fails:
09-10 09:45:00.314: E/log_tag(785): Error parsing data org.json.JSONException: Value {"stoker":{"sensors":[{"id":"620000116F01CA30","al":0,"tl":65,"tc":66.3,"ta":66,"name":"SS2","blower":null,"th":75},{"id":"E20000116F0CDB30","al":0,"tl":32,"tc":70.6,"ta":203,"name":"brskt2","blower":null,"th":32}],"blowers":[{"id":"37000000119D8B05","on":0,"name":"party"}]}} of type org.json.JSONObject cannot be converted to JSONArray
You can’t just parse JSON using the Java API without specifying Object or Array — a JSON document can be either. Since your data in the log shows an Object, you need to ask for a JSONObject on your second line.
So long as the JSON string in your logcat is accurate, there are two things that need to change. First, your result is a JSONObject that contains a JSONArray. You'll have to make an object first and extract the array from that object. Secondly, tc and ta are shown as doubles and integers respectively in the output and would need to be retrieved as such. It'd all look something like this:
try {
JSONObject obj = new JSONObject(result);
JSONObject stoker = obj.getJSONObject("stoker");
JSONArray jArray = stoker.getJSONArray("sensors");
for(int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Sensor resultRow = new Sensor();
resultRow.id = json_data.getString("id");
resultRow.name = json_data.getString("name");
resultRow.current = json_data.getDouble("tc");
resultRow.target = json_data.getInt("ta");
arrayOfWebData.add(resultRow);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
Based on the provided JSON string, this should work. For future reference, anything contained within {} is a JSONObject while anything inside of [] is a JSONArray. Any second value in a key/value pair that has quotes around it is likely a string while values without quotes are retrieved as numbers.

Categories

Resources