Getting value from nested JSON Array via GSON on Android? [duplicate] - java

This question already has answers here:
How to parse json parsing Using GSON in android
(5 answers)
Closed 2 years ago.
Context: I'm having trouble getting a value out of a JSON returned by OpenWeatherMap's API via Android.
My JSON looks like this:
{"coord":{"lon":-78.32,"lat":38.55},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"base":"stations","main":{"temp":269.05,"feels_like":265.34,"temp_min":267.59,"temp_max":270.37,"pressure":1010,"humidity":78},"visibility":10000,"wind":{"speed":1.25,"deg":293},"clouds":{"all":25},"dt":1607493640,"sys":{"type":3,"id":2006561,"country":"US","sunrise":1607516385,"sunset":1607550737},"timezone":-18000,"id":4744896,"name":"Ashbys Corner","cod":200}
It is stored in a JsonObject (Part of GSON, not to be confused with JSONObject) from a URL like so:
URLConnection requestWeather = weatherUrl.openConnection();
requestWeather.connect(); // connect to the recently opened connection to the OpenWeatherMaps URL
JsonElement parsedJSON = JsonParser.parseReader(new InputStreamReader((InputStream) requestWeather.getContent())); //Convert the input stream of the URL into JSON
JsonObject fetchedJSON = parsedJSON.getAsJsonObject(); // Store the result of the parsed json locally as a json object
Problem: I want to get the value associated with "main" out of the JSON (which in this case should be "Clouds").
Attempted Solution: I've attempted to get the value of main out like this:
String weatherType = fetchedJSON.get("weather").getAsString();
but this throws a java.lang.UnsupportedOperationException: JsonObject exception.
Question: How do I get the value of "main"?

You can use JACKSON or GSON library for fast parsing of Json data using model class.
JACKSON and GSON are dedicated to processing (serializing/deserializing) JSON data.
Raw Parsing via GSON
JsonObject fetchedJSON = parsedJSON.getAsJsonObject();
//weather is an array so get it as array not as string
JsonArray jarray = fetchedJSON.getAsJsonArray("weather");
// OR you use loop if you want all main data
jobject = jarray.get(0).getAsJsonObject();
String main= jobject.get("main").getAsString();
Although if you want raw parsing then you can do like ::
JSONObject obj = new JSONObject(yourString);
JSONArray weather = obj.getJSONArray("weather");
for (int i = 0; i < arr.length(); i++)
{
String main= arr.getJSONObject(i).getString("main");
......
}

Related

Find JSON object in JSON array

I have a goal to verify that certain JSON that I've got from RabbitMQ corresponds to one of expected JSONs in an array in a single file.
In other words, I need to verify that this JSON:
{
"networkCode":"network",
"programId":"92000"
}
is present in this JSON array:
[
{
"networkCode":"network",
"programId":"92000"
},
{
"networkCode":"network",
"programId":"92666"
}
]
Thank you very much for help!
Some part of my code
//GET DESIRABLE JSON
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
JSONObject myJSON= new JSONObject(message);
//GET THE JSON ARRAYS FROM FILE
JSONParser parser = new JSONParser();
Object expectedJSONs= parser.parse(new FileReader("C:\\amqpclient\\src\\test\\java\\tradeDoubler\\ExpectedDTO.json"));
JSONArray expectedArray = (JSONArray) expectedJSONs;
JSONAssert.assertEquals(
myJSON, expectedArray , JSONCompareMode.LENIENT);
Compilation says that cannot resolve this
Exception in thread "main" java.lang.AssertionError: Expecting a JSON array, but passing in a JSON object
Org.json library is quite easy to use.
Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" yourJSONObjectHere ");
JSONArray arr = obj.getJSONArray("networkArray");
for (int i = 0; i < arr.length(); i++)
{
String networkCode = arr.getJSONObject(i).getString("networkCode");
......
}
By iterating on your JSONArray, you can check if each object is equal to your search.
You may find more examples from: Parse JSON in Java
May I suggest you to use the Gson Library?
You can use something like this. But It will throw an exception if the json doesn't match/contains the fields.
Type listType = new TypeToken<ArrayList<YourJavaClassJsonModel>>() {
}.getType();
List<YourJavaClassJsonModel> resultList = gson.fromJson(JsonString, listType);
Hope it may help
You could use a JSON parser to convert the JSON to a Java object (Jackson and GSON are good options), and then check that object.

How to parse huge json data combiling multi level array by java

I am trying to parse huge JSON data. I can't give the JSON content here in this question. But you can see actual data at this link:-
https://drive.google.com/file/d/1p3lfaQ_k3C9DB3qA3W72IGiefwLUhCzm/view
I know there popular libraries like GSON and Jackson. I tired GSON as:-
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(line); // line contains all json data
But JsonElement has no suitable method to get data by json key.
My intentions is to parse the data which is a array in the json data. How can I do it?
JsonElement is the parent class for all nodes that the GSON parser returns. In your case the root node is a JsonObject, so it's safe to cast the element to that or use the convenience accessor getAsJsonObject.
JsonObject has the API you need for field access, and JsonArray has the API for array access:
JsonElement root = new JsonParser()
.parse(new FileReader("data.json"));
JsonArray data = root.getAsJsonObject()
.getAsJsonObject("dataset_data")
.getAsJsonArray("data");
System.out.println(data.size());
You can use this simple json library
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
It has user friendly interface that you are require if I understood you correctly like this
JSONObject obj = new JSONObject("jsoncontent");
JSONArray arr = obj.getJSONArray("arraykey");
Integer i=obj.getInt("someintegerfield");
JSONObject aob = obj.getJSONObject("anotherobject");

Parsing DBpedia JSON from localhost extraction server in java when the schema isn't known

This is probably a quick answer to a very novice question. I am having trouble wrapping my head around how to get JSON text dbpedia extraction server running from a localhost. The server is running fine, I followed the official instructions.
I have read the other StackOverflow questions about parsing JSON in java and what I am having trouble understanding is how to parse the JSON when the schema or structure is unknown.
For example in my code I try to grab the JSON from localhost and put it into a java object. But all the examples of parsing JSON online use a predesigned java object and all the JSON keys are mapped to an object's fields. (ie Employee class: name,job,email,id,phone)
String sURL = "http://localhost:9999/server/extraction/en/extract?title=" + wikipage + "&revid=&format=rdf-json&extractors=custom"; //just a string
URL url = new URL(sURL);
Reader pageReader = new InputStreamReader(url.openConnection().getInputStream());
Gson g = new Gson();
JsonReader jr = new JsonReader(new InputStreamReader((InputStream) request.getContent()));
jr.setLenient(true);
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
I now have this "json object" for the film "Blue Velvet" I can parse/iterate with jr.hasNext() or rootobj.getAsJsonArray().
Am I going about this correctly?
I feel like I am reinventing the wheel. Is there a standard way of parsing DBpedia JSON objects in Java?
At least the Jackson JSON library allows you to parse incoming JSON into a Map. If the keys and values of the JSON can be of any type, then you need to use Map<Object, Object>, which is a bit cumbersome, but anyways this should work:
ObjectMapper mapper = new ObjectMapper();
Map<Object, Object> parsedJSON = mapper.readValue(incomingJSON,
mapper.getTypeFactory().constructMapType(
LinkedHashMap.class,
Object.class,
Object.class));

How to have each record of JSON on a separate line?

When I use JSONArray and JSONObject to generate a JSON, whole JSON will be generated in one line. How can I have each record on a separate line?
It generates like this:
[{"key1":"value1","key2":"value2"}]
I need it to be like following:
[{
"key1":"value1",
"key2":"value2"
}]
You can use Pretty Print JSON Output (Jackson).
Bellow are some examples
Convert Object and print its output in JSON format.
User user = new User();
//...set user data
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
Pretty Print JSON String
String test = "{\"age\":29,\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"myname\"}";
Object json = mapper.readValue(test, Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
Reference : http://www.mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/
You may use of the google-gson library for beautifying your JSON string.
You can download the library from here
Sample code :
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);
OR
you can use org.json
Sample code :
JSONTokener tokener = new JSONTokener(uglyJsonString); //tokenize the ugly JSON string
JSONObject finalResult = new JSONObject(tokener); // convert it to JSON object
System.out.println(finalResult.toString(4)); // To string method prints it with specified indentation.
Refer answer from this post :
Pretty-Print JSON in Java
The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:
JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
and please refer this : https://stackoverflow.com/a/2614874/3164682
you can also beautify your string online here.. http://codebeautify.org/jsonviewer
For gettting a easy to read json file you can configure the ObjectMapper to Indent using the following:
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

JSON Parsing in Android [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I have searched alot on JSON Parsing in Android, but couldn't quite convinced. Actually got a brief idea but not so clear yet regarding JSON Parsing.
How to implement the JSON Parsing in the Application?
This is a very simple JSON String
{"key1":"value1","key2":"value2"}
In order to get values for it use JSONObject like this :
JSONObject json_obj=new JSONObject(your json string);
String value1=json_obj.getString("key1");
String value2=json_obj.getString("key2");
This is a slightly complex json string
[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}]
In order to extract values from this use JSONArray
JSONArray jArray=new JSONArray(your json string);
for(int i=0;i<(jArray.length());i++)
{
JSONObject json_obj=jArray.getJSONObject(i);
String value1=json_obj.getString("key1");
String value2=json_obj.getString("key2");
}
Hope this helps a bit...........
You can also check out Google's GSON library here. The GSON user guide here has some useful examples to help get you started. I've found GSON to be simple and powerful.
See: http://developer.android.com/reference/org/json/package-summary.html
Primarily, you'll be working with JSONArray and JSONObject.
Simple example:
try {
JSONObject json = new JSONObject(jsonString);
int someInt = json.getInt("someInt");
String someString = json.getString("someString");
} catch (JSONException e) {
Log.d(TAG, "Failed to load from JSON: " + e.getMessage());
}
You can use the org.json package, bundled in the SDK.
See here: http://developer.android.com/reference/org/json/JSONTokener.html
One more choice: use Jackson.
Simple usage; if you have a POJO to bind to:
ObjectMapper mapper = new ObjectMapper(); // reusable
MyClass value = mapper.readValue(source, MyClass.class); // source can be String, File, InputStream
// back to JSON:
String jsonString = mapper.writeValue(value);
to a Map:
Map<?,?> map = mapper.readValue(source, Map.class);
or to a Tree: (similar to what default Android org.json package provides)
JsonNode treeRoot = mapper.readTree(source);
and more examples can be found at http://wiki.fasterxml.com/JacksonInFiveMinutes.
Benefits compared to other packages is that it is lightning fast; very flexible and versatile (POJOs, maps/lists, json trees, even streaming parser), and is actively developed.

Categories

Resources