How to Read JSON File into Java with Simple JSON Library

What’s the best way to load a JSONObject from a json text file?

try this:

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;

public class JsonParsing {

public static void main(String[] args) throws Exception {
InputStream is =
JsonParsing.class.getResourceAsStream( "sample-json.txt");
String jsonTxt = IOUtils.toString( is );

JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
double coolness = json.getDouble( "coolness" );
int altitude = json.getInt( "altitude" );
JSONObject pilot = json.getJSONObject("pilot");
String firstName = pilot.getString("firstName");
String lastName = pilot.getString("lastName");

System.out.println( "Coolness: " + coolness );
System.out.println( "Altitude: " + altitude );
System.out.println( "Pilot: " + lastName );
}
}

and this is your sample-json.txt , should be in json format

{
'foo':'bar',
'coolness':2.0,
'altitude':39000,
'pilot':
{
'firstName':'Buzz',
'lastName':'Aldrin'
},
'mission':'apollo 11'
}

Read json file from resources and convert it into json string in JAVA

try(InputStream inputStream =Thread.currentThread().getContextClassLoader().getResourceAsStream(Constants.MessageInput)){
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readValue(inputStream ,
JsonNode.class);
json = mapper.writeValueAsString(jsonNode);
}
catch(Exception e){
throw new RuntimeException(e);
}

How to read json file into java with jackson library?

It should be nice to have the log files attached as text and not as image.

The problem should be in the json file.

According to your java classes the json file should be as follows:

 {
"id": 15,
"name": "Steve",
"data": {
"veek": "vect",
"seev": "vecs"
}
}

Note the object attribute change from "Datax" to "data".

How to read json file into java with GSON library

You try to convert a JsonObject to a JsonArray which cannot work, you need fist to get the root JsonObject then use getAsJsonArray(String memberName) to get the property tableRows as JsonArray as next:

...
// Get the root JsonObject
JsonObject je = jsontree.getAsJsonObject();
// Get the property tableRows as a JsonArray
JsonArray ja = je.getAsJsonArray("tableRows");
for (Object o : ja) {
...
// Warning JSON is case sensitive so use mailContent instead of mailcontent
String mail = person.get("mailContent").getAsString();
...
}

Output:

100
Test mail content 123
0
200
Test mail content 123
0
300
Test mail content 123
0

Java 8 JSON-simple - How can i read a subitem?

You have 1 "root" JSONObject, containing 3 nodes, each an instance of JSONObject. These 3 nodes each contains 2 nested nodes. json-simple will treat these as strings, if you traverse through the structure.

To print out the contents of your parents, you'd have to do something similar to:

JSONParser parser = new JSONParser();

JSONObject parents = (JSONObject) parser.parse(new FileReader("filename"));

JSONObject parent1 = (JSONObject) parents.get("PARENT1");
JSONObject parent2 = (JSONObject) parents.get("PARENT2");
JSONObject parent3 = (JSONObject) parents.get("PARENT3");

System.out.println("Parent 1");
System.out.println("\tChild 1: " + parent1.get("child_attr1"));
System.out.println("\tChild 2: " + parent1.get("child_attr2"));

System.out.println("Parent 2");
System.out.println("\tChild 1: " + parent2.get("child_attr1"));
System.out.println("\tChild 2: " + parent2.get("child_attr2"));

System.out.println("Parent 3");
System.out.println("\tChild 1: " + parent3.get("child_attr1"));
System.out.println("\tChild 2: " + parent3.get("child_attr2"));

This would ouput

Parent 1
Child 1: 0.00
Child 2: 0.30
Parent 2
Child 1: 0.10
Child 2: 0.12
Parent 3
Child 1: 0.03
Child 2: 0.45

If you want to be able to iterate over all the childs, you should define each parent as a JSONArray, and each child as a JSONObject

{
"PARENT1": [
{"child_attr1": "0.00"},
{"child_attr2": "0.30"}
],
"PARENT2": [
{"child_attr1": "0.10"},
{"child_attr2": "0.12"}
],
"PARENT3": [
{"child_attr1": "0.14"},
{"child_attr2": "0.45"}
]
}

If your structure would always follow this sample: 1 root object with x-amount parent array objects, each with y-amount child objects, where the child objects never have any nested nodes, one way to iterate over all of them would be:

Iterator<?> i = parents.keySet().iterator();
// Alternative, if you don't need the name of the key of the parent node:
// Iterator<?> i = parents.values().iterator();
while(i.hasNext()) {
String parentKey = (String) i.next();
JSONArray p = (JSONArray) parents.get(parentKey);
System.out.println(parentKey);

// If you don't need the name of the parent key node,
// replace the above with:
// JSONArray p = (JSONArray) i.next();
// Remember to use the alternative iterator-definition above as well

for(Object o : p) {
JSONObject child = (JSONObject) o;
System.out.println("\t" + child.keySet() + ": " + child.values());
}
}

The above (with the parent node names) would output:

PARENT1
[child_attr1]: [0.00]
[child_attr2]: [0.30]
PARENT3
[child_attr1]: [0.14]
[child_attr2]: [0.25]
PARENT2
[child_attr1]: [0.10]
[child_attr2]: [0.12]

When calling #keySet() and #values() on the child node, it will return as a Set and a Collection, respectively. When using #toString() on these, the output will be printed enclosed in brackets ([keys/values]). You can of course just ask for an array, and then the first entry, to get the lonely key/value: child.keySet().toArray()[0] and child.values().toArray()[0]. This won't of course work, if you have nested nodes inside your child nodes - in such case, it would only print the first key/value for the particular node.



Related Topics



Leave a reply



Submit