Android app to parse JSON from website - java

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.

Related

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.

Parser for json Object in java

I am trying to create a common parser in java.I am passing json object from different class based on my need.But parsing doesnot works for me.Can anybody help me to make a JSONObject parser in java.Any help will be highly appreciable....
This is my code for common parser
public JSONObject jsonParser(JSONObject objJson){
//JSONObject myjson = new JSONObject(objJson);
JSONArray the_json_array = objJson.getJSONArray("profiles");
JSONObject SnapshotRequest= objJson.g;
Iterator x = SnapshotRequest.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(songs.get(key));
}
}
In this code I am getting an error that need to cast.
JSONArray the_json_array = objJson.getJSONArray("profiles");
But casting won't work.

Json Iterating using java

Here is my json Object.
{"id":"mrbbt6f3fa99gld0m6n52osge0",
"name_value_list":
{"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"}},
"module_name":"Users"}
I got id,and module_name through following code.How can i get user_default_dateformat?.
I know it may so simple but I am a newbie in json.
String jsonResponse;
while ((jsonResponse = br.readLine()) != null) {
jsonOutput = jsonResponse;
}
JSONObject job = new JSONObject(jsonOutput);
System.out.println(job);// i can see the same json object
that i showen above.
sessionID = job.get("id").toString();
Exception generating coge
JSONObject job2=new JSONObject(job);
dateFormat = job2.get("user_default_dateformat").toString();
The Eexception is
org.json.JSONException: JSONObject["user_default_dateformat"] not found.
Thanks,
name_value_list is also an Object.
JSONObject job2 = new JSONObject(job.get("name_value_list"));
So there you get
job2.get("user_default_dateformat");
Every {} in your JSON is an object. So for every String you get which is something like {"xy":"za","ab":"cd"} you have to cast it to the JSONObject
Edit for your error:
As you can see in your code the line:
JSONObject job2=new JSONObject(job);
will try to generate a JSONObject out of your JSONObject.
You have to get the JSONObject in your JSONObject.
You want to get the user_default_dateformat which is in your JSONObject:
String name_value_list_string = job.get("name_value_list").toString();
//this string is another json-string which contains the user_default_dateformat
JSONObject name_value_list_object = new JSONObject(name_value_list_string);
//This JSONObject contains the user_default_dateformat but this is also a JSONObject
String user_default_dateformat_string = name_value_list_object.get("user_default_dateformat").toString();
//this String contains the user_default_dateformat JSONString
JSONObject user_default_dateformat_object = new JSONObject(user_default_dateformat_string);
//This JSONObject contains the String values of your user_default_dateformat
if you are using JSONSimple library you can use this:
jsonObject = (JSONObject) new JSONParser().parse(jsonstr);
System.out.println((JSONObject)jsonObject.get("name_value_list"))).get("user_default_dateformat"));
This should give you the required result.

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.

parsing URL in String from JSON

1) I've got a JSON file:
{
"serverURI":"http://localhost:8080/PocketUNI_API/serverURLs",
"newsURI":"http://localhost:8080/gateway/rss/rss.xml",
"modulesURI":"http://localhost:8080/PocketUNI_API/modules"
}
2) I need to get URLs on Java client in String format.
String json = jsonReceiver.makeHttpRequest(URL_SERVER, "GET", params);
JSONArray uris = new JSONArray(json);
Receiver works fine and json shows the correct string received, but when it goes to parsing with JSONArray it throws an error
org.json.JSONException: Value {"serverURI":"http:\/\/192.168.0.... of type org.json.JSONObject cannot be converted to JSONArray.
Question: How to parse json with URL values?
You don't get a JSONArray but a JSONObject.
JSONObject uris = new JSONObject(json);
json is a json object not an array, that is why you are getting the error. An array will be wrapped with in [ and ], and objects within { and }.
JSONObject uris = new JSONObject (json);
Instead of JSONArray you must use JSONObject.
JSONObject uris = new JSONObject(json);
In your code just replace JSONArray to JSONobject
JSONObject uris = new JSONObject(json);

Categories

Resources