Get array with json object out of a string - java

I have a java spring boot project that makes an REST API call and one element of the returned json is as follows:
"args": "[[\"element_1\"],[\"element_2\"],[\"{\\\"payload\\\":\\\"{\\\"Header\\\": \\\"Header_title\\\", \\\"Content\\\": \\\"Content of the payload\\\"}\\\"}\"]]"
My objective is to get the JsonObject "payload". I can get the string using
JsonObject argString = (JsonObject) jsonParser.parse(originalJsonObject.get("args").toString());
(using the package com.google.gson.JsonObject) but I can't get the two-dimensional array out of the string.

The part of data that you've included actually is a key args with a string value [[\"element_1\"],[\"element_2\"],[\"{\\\"payload\\\":\\\"{\\\"Header\\\": \\\"Header_title\\\", \\\"Content\\\": \\\"Content of the payload\\\"}\\\"}\"]]. So it is correct that you cannot get these contents decoded through a method on the existing Json, but you can take the string and parse it to a json array as follows:
JsonElement jsonElem = new JsonParser().parse(argString);
JsonArray jsonArray = jsonElem.getAsJsonArray();
for(int i = 0; i < jsonArray.size(); i++) {
System.out.println(jsonArray.get(i));
}

Related

How to extract json Objects from String Builder?

I have string builder of the form:
[{"abc" : ["something1", "something2"]}, {"def" : ["something3", "something4"]}]
How do I convert it so that I can perform get on the keys? For e.g.: object.get("abc") and i get the list back.
I looked around for solutions:
I tried doing:
JSONObject jsonObject = new JSONObject(sb.toString());
I get the following exception:
exception org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
I then tried taking a sub-string of the Json, like this:
JSONObject jsonObject = new JSONObject(sb.toString().substring(1, sb.toString().length()-1));
which gives back:
jsonObjwct {"Z-DwY2Ul":["Worried Blues","Worried Blues"]}
I get only the first object, i need all of them.
What modifications i can do to get the list back for a specific key?
It is a JSONArray of JSONObject's, so first convert it into JSONArray
JSONArray array = new JSONArray(sb.toString());
And then you can iterate by using for loop
for (int i = 0, size = array.length(); i++) {
JSONObject obj = array.optJSONObject(i); //{"abc" : ["something1", "something2"]}
}

JSONArray initial value should be a string or collection or array while parsing a JSON Array in java

I have a JSON with the below structure:
[
{
"timestamp": "2019-07-12 00:29:37",
"OutletTemperatureCV": "31.5",
"ChocolateMixingTemperatureCV": "30.399999",
"WaterCoolingTemperatureCV": "13.899",
"WaterMixingTemperatureCV": "31.5"
}
]
The Json file is named as temperer. I am trying to parse this json array to get values values.
JSONArray array1=new JSONArray(temperer);
for (int n = 0; n < array1.length(); n++) {
JSONObject jsonObject = array1.getJSONObject(n);
String time= jsonObject.getString("timestamp");
String outletTemp= jsonObject.getString("OutletTemperatureCV");
String outletTemp= jsonObject.getString("ChocolateMixingTemperatureCV");
String outletTemp= jsonObject.getString("WaterCoolingTemperatureCV");
String outletTemp= jsonObject.getString("WaterMixingTemperatureCV");
}
But when I try this code, I get the below error..
org.json.JSONException: JSONArray initial value should be a string or
collection or array.
I saw another post in SO with a similar prob, but this example uses a named JSON array.
(Parsing JSON Array within JSON Object)
How can I get over this error for an unnamed JSON array?
Any solutions will be hugely helpful :(

Extract data from json string with or without JSONObject

I've got the following json code stored in a java String:
String str = {"posts":[{"key":"key1","value":"x"},{"key":"key2","value":"0"},{"key":"key3","value":"y"}]}
Is there a way to extract the values from the string using JSONObject or should I use the old school method:
String[] parts = str.split("\"");
In my case the values are stored in the array at the positions: parts[9], parts[17] and parts[25].
It works well so far, but I wonder if I could use JSONObject for that task?
Using JSONObject (from the org.json package, JSON-java), you can easily extract values.
final JSONObject jsonObject = new JSONObject(str);
final JSONArray posts = jsonObject.getJSONArray("posts");
final Collection<String> values = new ArrayList<>(posts.length());
for (int i = 0; i < posts.length(); i++) {
final JSONObject post = posts.getJSONObject(i);
values.add(post.getString("value"));
}
// values = [x, 0, y]
I'd absolutely avoid any kind of manual String manipulation.
Use Gson library provided by google if you are using Java
https://github.com/google/gson
Here you can convert your java to Json and Json back to java objects seamlessly.

converting from String to JSONArray or JSONObject in Java

I'm trying to use the JSON library to consume twitter information from the get search feature. I'm getting the error:
A JSONArray text must start with '[' at 1 [character 2 line 1]
So it's basically in the wrong form. Some people are saying this needs to be an object but everytime I call the constructor it says that it can't take a String as input. How do I get this string into the form of a JSONArray so that I can access it's elements.
Here is my code:
URL twitterSource = new URL("http://search.twitter.com/search.json?q=google");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(twitterSource.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();
// parse JSON
System.out.println(urlContents);
JSONArray jsonArray = new JSONArray(urlContents);
// use
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at"));
}
my print statement shows the string contains:
{"completed_in":0.318,"max_id":144850937012428800,"max_id_str":"144850937012428800","next_page":"?page=2.....................
This is a string in the form of a JSON object but it is not actually an object. It's still a string. I'm printing a String. HOw can I get this into an Object or better yet a JSONArray so that I can actually access its elements.
That's a JSON object, not an array.

org.json.JSONException: "JSON object not found in JSON array"

A very simple JSON like this (response.getBody().toString()):
{"per_page":50,"total":93,"last_page":2,"stars":[]}
Has some problems when I want to parse it:
JSONObject object = new JSONObject(response.getBody()); // no error
System.out.println(object.getJSONObject("total")); // not found
org.json.JSONException: JSONObject["total"] not found.
Other properties cannot be parsed either:
JSONArray startups = object.getJSONArray("stars");
org.json.JSONException: JSONObject["stars"] not found.
The key is to hold the value of response.getBody()
String json = response.getBody().toString();
Inside object total is not JSONObject it is an Int value, that's why you code crashing.
So use this
System.out.println(String.valueOf(object.getInt("total")));
instead of
System.out.println(object.getJSONObject("total"));
String json = "{\"per_page\":50,\"total\":93,\"last_page\":2,\"stars\":[]}":
JSONObject jsonObject = new JSONObject (json);
JSONArray jsonArray = jsonObect.getJSONArray("stars");
int perPage = jsonObject.getInt("per_page");
try like this...
In addition to earlier answer, to parse array, use getJSONArray as
JSONArray ja = jsonObj.getJSONArray("stars");
You can loop-over the array as:
for(int j=0; j<ja.length(); j++) {
JSONObject json = ja.getJSONObject(j);
// do same as before for string, int or other data types
}

Categories