Why does my JSON-Simple JSONArray give me a nullpointer exception? - java

I'm following this tutuorial here, and my JSON object is near enough the same, except I have this sort of format:
{"user":{
"SomeKeys":"SomeValues",
"SomeList":["val1","val2"]
}
}
Here is my relevant code:
Object obj = parser.parse(new FileReader("exampleJson.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject user = (JSONObject) jsonObject.get("user");
JSONArray list = (JSONArray) user.get("SomeList");
Then my program goes off an gets the values form the keys etc. Or it would but I get a NullPointerException from eclipse. Why is this?
It should unpackage my .json file into jsonObject, unpackage the "user" key as a JSONObject user, then unpackage the "SomeList" key as a JSONArray called list. Except when it does so it must be trying to put one of val1 or val2 into a part of the JSONArray that does not exist and just points into the abyss of null. What have I done to deserve this wrong ?
How do I fix my program?

Your code is working well for me
public class App {
public static void main(final String[] args) throws FileNotFoundException, IOException, ParseException {
final Object obj = new JSONParser().parse(new FileReader("D:/a.json"));
final JSONObject jsonObject = (JSONObject) obj;
final JSONObject user = (JSONObject) jsonObject.get("user");
final JSONArray list = (JSONArray) user.get("SomeList");
System.out.println(list);
}
}
File D:/exampleJson.json
{"user":{
"SomeKeys":"SomeValues",
"SomeList":["val1","val2"]
}
}
output is
["val1","val2"]

Using the exact same json file:
{"user":{
"SomeKeys":"SomeValues",
"SomeList":["val1","val2"]
}
}
Here is the code I use (with the imports to really make sure we have the same ones):
import java.io.FileReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Test {
public static void main(String[] args) throws Exception {
Object obj = new JSONParser().parse(new FileReader("t.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject user = (JSONObject) jsonObject.get("user");
JSONArray list = (JSONArray) user.get("SomeList");
System.out.println(list);
}
}
And here is the output:
["val1","val2"]
I used maven and m2e to import the library. The version used for this test was json-simple-1.1.jar.

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"}

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

add JSONArray within a JSONObject

I'm making an application to send notifications using OneSignal and must do a POST request in JSON format.
To send notification to a user I have to use the include_player_ids argument which have to be an array because it is possible to send to multiple users the same notification (in my case I only send notification to one user).
I use a JSONArray to create this array but when adding it to the JSONObject, there are extra quotes for the field include_player_ids.
What I have:
{
"headings": {"en":"my_title"},
"contents": {"en":"my_text"},
"include_player_ids": "[\"my-player-id\"]",
"app_id":"my-app-id"
}
As you can see, there is some quote around the array [ ].
I guess it's what is making the response error from OneSignal :
errors":["include_player_ids must be an array"]
What I want :
...
"include_player_ids": ["my-player-id"]
...
It is weird because adding JSONObject to JSONObject doesn't do this even though it is quite similar as you can see with the headings / contents fields
My code :
import org.json.JSONException;
import org.json.JSONObject;
import org.json.alt.JSONArray;
JSONObject headings = new JSONObject();
JSONObject contents = new JSONObject();
JSONArray player_id = new JSONArray();
JSONObject notification = new JSONObject();
try {
notification.put("app_id", appId);
notification.put("include_player_ids", player_id);
player_id.put(idUser);
headings.put("en", "my_title");
contents.put("en", "my_text");
notification.put("headings", headings);
notification.put("contents", contents);
} catch (JSONException e) {
System.out.println("JSONException :" + e.getMessage());
}
idUser is a String
Thanks in advance for any help,
I believe the problem is that you're using org.json.alt.JSONArray instead of org.json.JSONArray. I'm not familiar with that class, but I suspect JSONObject.put is just calling toString() on it rather than treating it as an existing JSON array. Here's a short but complete example that doesn't have the problem:
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray; // Note the import here
public class Test {
public static void main(String[] args) throws JSONException {
JSONArray playerIds = new JSONArray();
playerIds.put("a");
playerIds.put("b");
JSONObject notification = new JSONObject();
notification.put("include_player_ids", playerIds);
System.out.println(notification);
}
}
Output:
{"include_player_ids":["a","b"]}

parse json string using simple-json

I have read the posts that appeared to be the same as my question but I must be missing something. My environment is Eclipse Mars. My JAVA is 1.7 and I have imported json-simple. I simply wish to parse the json that is returned from my web service. I control the web service if I need to modify its output. I see the json in arg[0] as noted below however the Object obj is null as of course is the JSONArray array. I know that I am missing something basic but I am stumped and a bit tired.
Here is the returned json:
[{"$id":"1","NumberID":121183,"PortfolioID":718,"PropertyID":14489,"Adsource":17287,"PlanTypeID":1,"GreetingFile":"HolidayGreeting.wav","PromptFile1":"senior.leasing.first.wav","Accepts1":2,"PromptAction_ID1":1,"PromptFile2":"Default.wav","Accepts2":2,"PromptAction_ID2":1,"PromptFile3":"Default.wav","Accepts3":2,"PromptAction_ID3":1,"PromptFile4":"Default.wav","Accepts4":2,"PromptAction_ID4":1,"PromptFile5":"Default.wav","Accepts5":2,"PromptAction_ID5":1,"HoldMsgFile1":"SpectrumHold.wav","HoldMsgFile2":"Default.wav","Destination1":15197,"Destination2":15024,"Destination3":0,"UIType_ID":16,"RingCount":0,"Enabled":true,"Spanish":false,"HoldMusicFile":"Hold_Music.wav","Template_ID":41,"FrontLineForward":true,"DisclaimerFIle":"1Silence.wav"}]
Here is the parse code employing json-simple:
package parser;
import org.json.simple.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
public class JsonParser
{
private static JSONObject _jsonInput;
public static void main(String[] args)
{
//TODO
try{
JSONParser parser = new JSONParser();
Object obj = JSONValue.parse(args[0]);
JSONArray array=(JSONArray)obj;
String name = array.get(3).toString();
System.out.println(obj);
}
catch(Exception e){
e.printStackTrace();
}
}
}
The size of the array different than the index used
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(args[1]));
JSONArray array=(JSONArray)obj;
if (array.size() > 3)
String name = array.get(3).toString();

Categories