get nested Object using json-simple - Wildcard for parent Node - java

I want to retrieve "name" values and store them in an Arraylist from a JSON file in Java. I am using JSON-simple library Here is an example of my "file.json":
{
"111": {
"customer": {
"name": "John Do",
"Height": 5.9,
"City": "NewYork"
}
},
"222":{
"customer": {
"name": "Sean Williams",
"Height": 6,
"City": "Los Angeles"
}
}
}
Id numbers "111" and "222" are not significant for my program and they are randomly generated so I am not able to use jObject.get() as the values will constantly be changing. I tried searching for a wildcard for the parent Node and then go to child node customer and then name but haven't found such thing.
Here is my code so far:
import java.io.*;
import java.util.ArrayList;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class npTest {
public static void main(String[] args) throws IOException, ParseException {
try {
JSONParser jParser = new JSONParser();
JSONObject jObject = (JSONObject) jParser.parse(new FileReader("file.json"));
//Notes
} catch (FileNotFoundException e) {
System.out.print("File not found!");
}
}
}
Notes: methods I have tried require jObject.get("id"). Also I noticed I am not able to store the JSONObject in another JSONObject, for example: JSONObject parentObj = new JSONObject(jObject.get("111"));

You can iterate through the keys in a JSONObject using the keySet() method. Then pull out your "customer" and get their name.
JSONParser jParser = new JSONParser();
JSONObject jObject = (JSONObject) jParser.parse(new FileReader("c:\\file.json"));
for(Object key : jObject.keySet()) {
JSONObject customerWrapper = (JSONObject)jObject.get(key);
JSONObject customer = (JSONObject)customerWrapper.get("customer");
System.out.println(customer.get("name"));
}

JSONObject implements the Map interface. So you could query for all map keys with normal Java syntax:
for (Object innnerO : jObject.values()){
JSONObject customerO = (JSONObject)((JSONObject)innerO).get("customer");
}
Note: This is written out of my head without compiler. So there might me errors.

Related

How to create Array of Objects using the Jackson Streaming API

I am trying to create a JSON using the Jackson Streaming API. I know how to create an array of elements in JSON using Jackson as we have plenty of examples related to it. But I am a bit confused about how to create an array of Objects using it.
Following is the JSON structure that I would like to obtain at the end:
{
"name" : "Batman",
"year" : 2008,
"writers":[
{
"name" : "Nolan",
"age" : 49
},
{
"name" : "Johnathan",
"age" : 35
}
]
}
Following is the code I have:
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HelloWorld {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
ByteArrayOutputStream jsonStream = new ByteArrayOutputStream();
JsonGenerator jsonGenerator = mapper.getFactory().createGenerator(jsonStream, JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Batman");
jsonGenerator.writeNumberField("year", 2008);
jsonGenerator.writeFieldName("writers");
jsonGenerator.writeStartArray();
// How to to create here objects and add it to the "writers"
// Should I create another JsonGenerator and create objects usign it?
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
String jsonData = new String(jsonStream.toByteArray(), "UTF-8");
JSONObject json = new JSONObject(jsonData);
System.out.println(json.toString(4));
}
}
Can someone please guide me on how to create the objects and add them to the array one by one? I am unable to find such an example so posting here.
I would just create a Map to store the data. For the writers, you can call List.of to create an in-line List.
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.databind.*;
public class MovieDataWriter {
public static void main(String[] args) {
Map<String, Object> movieData = createMap(
"name", "Batman",
"year", 2008,
"writers", List.of(
createMap(
"name", "Nolan",
"age", 49
),
createMap(
"name", "Johnathan",
"age", 35
)
)
);
writeToFile(movieData, "target/batman.json");
}
private static void writeToFile(Map<String, Object> data, String filename) {
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
try {
writer.writeValue(new File(filename), data);
} catch (IOException e) {
e.printStackTrace();
}
}
private static Map<String, Object> createMap(Object ...args) {
Map<String, Object> pairs = new LinkedHashMap<>();
for (int i = 0; i < args.length; i += 2) {
pairs.put(String.valueOf(args[i]), args[i + 1]);
}
return pairs;
}
}
Dependencies
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
batman.json
{
"name" : "Batman",
"year" : 2008,
"writers" : [ {
"name" : "Nolan",
"age" : 49
}, {
"name" : "Johnathan",
"age" : 35
} ]
}
After trying a few things I was able to get it. Basically, I had to do the same thing which I was asked in the question. I am not sure why it did not work the first time maybe I missed something. Anyways here is how you can add objects into the array using the Jackson Streaming API. Posting this as it can be beneficial to someone else in the future.
I am creating an array writers in this case and adding the objects into it using the same jsonGenerator.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HelloWorld {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
ByteArrayOutputStream jsonStream = new ByteArrayOutputStream();
JsonGenerator jsonGenerator = mapper.getFactory().createGenerator(jsonStream, JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Batman");
jsonGenerator.writeNumberField("year", 2008);
jsonGenerator.writeFieldName("writers");
jsonGenerator.writeStartArray();
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Nolan");
jsonGenerator.writeNumberField("age", 45);
jsonGenerator.writeEndObject();
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Johanathan");
jsonGenerator.writeNumberField("age", 35);
jsonGenerator.writeEndObject();
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
String jsonData = new String(jsonStream.toByteArray(), "UTF-8");
JSONObject json = new JSONObject(jsonData);
System.out.println(json.toString(4));
}
}
You will get the output something like this:
{
"year": 2008,
"name": "Batman",
"writers": [
{
"name": "Nolan",
"age": 45
},
{
"name": "Johanathan",
"age": 35
}
]
}

How to remove json key value pair from json object array using java

I want to remove "status": "new" from JSON that I have stored in jsonObject using
JSONParser parser = new JSONParser();
Object obj = parser.parse(responseStr);
jsonObject = (JSONObject) obj;
JSON structure --
{"actionName": "test"
"Data": [{
"isActive": true,
"Id": "1358",
"status": "new"
}],
}
new JSON should look like this -
{"actionName": "test"
"Data": [{
"isActive": true,
"Id": "1358"
}],
}
I have tried jsonObj.remove("status") , but no luck.
jsonObj.getJSONArray("Data").get(0).remove("status);
#Updated Code-breakdown:
JSONObject obj= (JSONObject) jsonObj.getJSONArray("Data").get(0);
obj.remove("status");
JSONArray newArr=new JSONArray();
newArr.put(obj);
jsonObj.put("Data", newArr);
It should do your work, haven't tested though.
First, your Data is JSONArray, retrieving that by jsonObj.getJSONArray("Data"), then access the array with get(0)[assuming, your array will contain only one entry like your example] and finally, removing that key by remove method.
You need to iterate over Data property which is a JSON Array and remove for every item status key.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.File;
import java.io.FileReader;
public class JsonSimpleApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
JSONParser parser = new JSONParser();
JSONObject root = (JSONObject) parser.parse(new FileReader(jsonFile));
JSONArray dataArray = (JSONArray) root.get("Data");
dataArray.forEach(item -> {
JSONObject object = (JSONObject) item;
object.remove("status");
});
System.out.println(root);
}
}
Above code prints:
{"Data":[{"Id":"1358","isActive":true}],"actionName":"test"}

Read JSON data in Java using the org/json/json/20171018 repository

I'm trying to read a JSON file in my java application using the org/json/json/20171018 repository (http://central.maven.org/maven2/org/json/json/20171018/ -> json-20171018.jar). My JSON file looks like this:
{
"manifest_version": 2,
"name": "Chrome Extension",
"version": "0.1",
"permissions": [
"tabs"
],
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"background": {
"matches": [
"google.de",
"youtube.com",
"wikipedia.de"
],
"scripts": ["background.js"],
"persistent": true
}
}
I'm interested in the background section more specific in the links the background matches to. So I've created first a JSONObject of the whole file, then a JSONObject of the background section and then a JSONArray of the type matches. But unfortunately I'm getting this error showing up when I run the program:
Exception in thread "main" org.json.JSONException: JSONObject["matches"] not found.
at org.json.JSONObject.get(JSONObject.java:520)
at org.json.JSONObject.getJSONArray(JSONObject.java:714)
at Json.main(Json.java:19)
My java code looks like this:
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Json {
public static void main(String[] args){
String loc = new String("chromeAdon/manifest.json");
File file = new File(loc);
try {
String content = new String(Files.readAllBytes(Paths.get(file.toURI())));
JSONObject json = new JSONObject(content);
JSONObject json2 = new JSONObject(json.getJSONObject("background"));
JSONArray jarray = json2.getJSONArray("matches");
for (int i=0;i<jarray.length();i++){
System.out.println(jarray.getString(0));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Does anyone know where my mistake is?
You are wrapping the JSON object returned by getJSONObject("background"), which is not needed.
Try just using the returned object:
JSONObject jsonContent = new JSONObject(content);
JSONObject jsonBackground = jsonContent.getJSONObject("background");
JSONArray jsonArrayMatches = jsonBackground.getJSONArray("matches");

How to replace "emailRecipients" key value from a json object in java

I need to replace emailRecipients value with some other value.
Here is JSON
{"payload": {"injectedDetails": "{\"injectedDetails\":\"test\"}","originalPayload": "{\"messageId\":\"232342",
\"emailRecipients\":[\"test#abc.com\"]}"},
"status": "OK"
}
I Tried below, but its putting a new key rather than replacing the existing once.even tried with putOnce()
jsonObjOriInj=new JSONObject(jsonobjectString);
jsonObjOriInj.put("emailRecipients", "2323");
Your JSON is not valid, but assuming JSON should be in following format,
{
"payload": {
"injectedDetails": {
"injectedDetails": "test"
}
},
"originalPayload": {
"messageId": "232342",
"emailRecipients":[
"test#abc.com"
]
},
"status": "OK"
}
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Main {
public static void main(String[] args) throws ParseException {
String data = "{\"payload\":{\"injectedDetails\":{\"injectedDetails\":\"test\"}},\"originalPayload\":{\"messageId\":\"232342\",\"emailRecipients\":[\"test#abc.com\"]},\"status\":\"OK\"}";
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(data);
//get originalPayload object
JSONObject originalPayload = (JSONObject) jsonObject.get("originalPayload");
// create new json array
JSONArray newEmailRecipients = new JSONArray();
// add new email recipients
newEmailRecipients.add("updated_test#abc.com");
// update originalPayload object with new emailRecipients
originalPayload.put("emailRecipients", newEmailRecipients);
// update JSON with updates originalPayload object
jsonObject.put("originalPayload", originalPayload);
System.out.println(jsonObject);
}
}
Output:
{"payload":{"injectedDetails":{"injectedDetails":"test"}},"originalPayload":{"messageId":"232342","emailRecipients":"[updated_test#abc.com]"},"status":"OK"}

How to get values inside from an array which is inside of an object?

I want to get the values of latitude and longitude from the JSON, which consists of two objects "stoppage" & "routePlaceback", now I'm able to get data from "routePlaceback" only, but I have no clue how to get only the values of latitude and longitude? code is as follows,
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Finder_Json
{
#SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception
{
// parsing JSON file
Object sampleFile_object = new JSONParser().parse(new FileReader("sample.json"));
// typecasting object to JSONObject
JSONObject sampleFile_JSONObject = (JSONObject) sampleFile_object;
JSONArray routePlaceback = (JSONArray) sampleFile_JSONObject.get("routePlaceback");
Iterator iterator_1 = routePlaceback.iterator();
while (iterator_1.hasNext())
{
System.out.println(iterator_1.next());
System.out.println("\n");
}
}
}
My sample.json file consists,
{
"stoppage":
[
{
"latitude": "23.074207",
"longitude": "72.557227",
"record_date": 1556217000,
"start_time": 1556217000,
"end_time": 1556304360,
"duration_time": 1456
}
],
"routePlaceback":
[
{
"distance": 0.36,
"longitude": "72.502385",
"ignition": 1,
"record_date": 1556303400,
"speed": 53.708,
"latitude": "23.034403"
},
{
"distance": 0.38,
"longitude": "72.506072",
"ignition": 1,
"record_date": 1556303430,
"speed": 25.927999,
"latitude": "23.034045"
}
]
}
This is what I get when I run the above code,
But my desired output is as,
23.034403, 72.502385
23.034045, 72.506072
You can extract the required values while displaying:
while (iterator_1.hasNext())
{
JSONObject obj = (JSONObject) iterator_1.next()l
System.out.println(obj.get("latitude")+" , "+obj.get("longitude"));
System.out.println("\n");
}
You are trying to access the property of an Object where you can get the Object.
while (iterator_1.hasNext())
{
JSONObject k= (JSONObject)iterator_1.next()
System.out.println(k.latitude+" "+k.longitude);
System.out.println("\n");
}
I modified a little bit your code to achieve your target. Please find the example below:
import java.io.FileReader;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Finder_Json
{
#SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception
{
// parsing JSON file
Object sampleFile_object = new JSONParser().parse(new FileReader("src/main/resources/sample.json"));
// typecasting object to JSONObject
JSONObject sampleFile_JSONObject = (JSONObject) sampleFile_object;
JSONArray routePlaceback = (JSONArray) sampleFile_JSONObject.get("routePlaceback");
Iterator iterator = routePlaceback.iterator();
while (iterator.hasNext()) {
JSONObject objt = (JSONObject) iterator.next();
System.out.println(objt.get("latitude") + ", " + objt.get("longitude"));
}
}
}
I strongly suggest to use Other libraries like GSON or Jackson anyway.

Categories