How to replace "emailRecipients" key value from a json object in java - 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"}

Related

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 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.

how to convert stringified JSONObject[] to JSONObj[] in java

I have JSONObject[] in stringified format. I need to convert it back to JSONObject[] in java how I can achive that??
Sample Code :
JSONObject[] json = new JSONObject[10];
String jsonStrArray = "[{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3}]";
JsonParser parser = new JsonParser();
JsonObject jo = (JsonObject)
parser.parse(strFinalRecord).getAsJsonObject();
json = jo;
Error:
incompatible type
Required : org.json.JsonObject[]
Found : com.google.gson.JsonObject
If it is getting gson.JsonObject how to can I cast it to JsonObject[] ?
Please help me to resolve this issue
The json String you have created is not formatted correctly.
Try the following code.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonTest {
public static void main(String arg[]) throws ParseException {
JSONObject json = new JSONObject();
String jsonStrArray = "[{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"},{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"},{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"}]";
JSONParser parser = new JSONParser();
JSONArray jo = (JSONArray) parser.parse(jsonStrArray);
System.out.println(jo);
json.put("key", jo);
System.out.println(json);
}
}
Use JSON-Simple

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

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.

Categories