Can't parse some JSON into a JsonArray using GSON - java

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.

Related

JSONObject from Google Maps parse in Java

I'm trying to parse Java Object to get data from a URL. I'm using getJSONObject and getString methods from org.json.JSONObject library but this it's not working. I'm doing something like...
JSONObject jsonCoord = json.getJSONObject("results")
.getJSONObject("geometry")
.getJSONObject("location");
coordinates[0] = jsonCoord.getString("lat");
coordinates[1] = jsonCoord.getString("lng");
JSON document I want to parse (Part 1)
JSON document I want to parse (Part 2)
How can I get "lat" and "lng" which is inside of "geometry"?
Here it is:
public static void main(String args[]) throws Exception {
String content = new String(Files.readAllBytes(Paths.get("test.json")), "UTF-8");
JSONObject json = new JSONObject(content);
JSONArray results = json.getJSONArray("results");
JSONObject result = (JSONObject) results.get(0); //or iterate if you need for each
JSONObject jsonCoord = result.getJSONObject("geometry").getJSONObject("location");
System.out.println(jsonCoord);
String[] coordinates = new String[2];
coordinates [0] = jsonCoord.getString("lat");
coordinates[1] = jsonCoord.getString("lng");
System.out.println(Arrays.asList(coordinates));
}

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.

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.

Categories

Resources