I'm using javax.json and when I tried change jsonObject in my jsonArray:
String jsonString = "[{\"name\":\"xyz\"," +
"\"URL\":\"http://example.com\"}]";
JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
JsonArray jsonArray = jsonReader.readArray();
String jsonNewString = "{\"name\":\"zyx\","
+ "\"URL\":\"http://example2.com\"}]";
jsonReader = Json.createReader(new StringReader(jsonNewString));
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
jsonArray.remove(0);
jsonArray.add(0, jsonObject);
I got this exception:
java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
I also tried: jsonArray.set(0, jsonObject);, and got the same UnsupportedOperationException.
The javadoc of JsonArray states
JsonArray represents an immutable JSON array (an ordered sequence of
zero or more values). It also provides an unmodifiable list view of
the values in the array.
You can't change it. Create a new one with the value(s) you want.
JsonObject and JsonArray are immutable so you cannot modify the object , you can use this example and try to inspire from it :
creation of a new JsonObject who contains the same values and add some elements to it ..
Example :
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.json.JsonValue;
public class Jsonizer {
public static void main(String[] args) {
try {
String s = "{\"persons\": [ {\"name\":\"oussama\",\"age\":\"30\"}, {\"name\":\"amine\",\"age\":\"25\"} ]}";
InputStream is = new ByteArrayInputStream(s.getBytes());
JsonReader jr = Json.createReader(is);
JsonObject jo = jr.readObject();
System.out.println("Before :");
System.out.println(jo);
JsonArray ja = jo.getJsonArray("persons");
InputStream targetStream = new ByteArrayInputStream("{\"name\":\"sami\",\"age\":\"50\"}".getBytes());
jr = Json.createReader(targetStream);
JsonObject newJo = jr.readObject();
JsonArrayBuilder jsonArraybuilder = Json.createArrayBuilder();
jsonArraybuilder.add(newJo);
for (JsonValue jValue : ja) {
jsonArraybuilder.add(jValue);
}
ja = jsonArraybuilder.build();
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
jsonObjectBuilder.add("persons", ja);
JsonObject jsonAfterAdd = jsonObjectBuilder.build();
System.out.println("After");
System.out.println(jsonAfterAdd.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output :
Before :
{"persons":[{"name":"oussama","age":"30"},{"name":"amine","age":"25"}]}
After
{"persons":[{"name":"sami","age":"50"},{"name":"oussama","age":"30"},{"name":"amine","age":"25"}]}
Related
I'm trying to read user id and user role from the following JSON file :
[https://drive.google.com/file/d/1X6t2kKaYArwM-mLc4EQhPAfUWF95RYTW/view?usp=sharing][1]
I have added both erp.json and class file in the same package : com.tpg.json
I'm using json simple jar file.
And facing the error : org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
Could you suggest me the edits and re-post the code?
You can post your code or another code as well,which will give me the required output.
package com.tpg.json;
import java.io.File;
import java.io.FileReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
//com.googlecode.json-simple
public class JsonParsing {
public static void main(String[] args) {
ClassLoader classLoader = new JsonParsing().getClass().getClassLoader();
String fileName = "com/tpg/json/erp.json";
File file = new File(classLoader.getResource(fileName).getFile());
JSONParser parser = new JSONParser();
try {
FileReader reader = new FileReader(file.getAbsolutePath());
Object obj = parser.parse(reader);
JSONObject jsonObj = (JSONObject) obj;
JSONObject res = (JSONObject) jsonObj.get("Resources");
System.out.println("studentDetails :" + res.toJSONString());
JSONArray ID = (JSONArray) res.get("id");
System.out.println("Id" + ID);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have JSONArray in String format as follows :
{
"productsList": [{
"map": {
"productSubcategory": "Levensverzekering",
"nameFirstInsured": "Akkerman"
}
},
{
"map": {
"productSubcategory": "Lineair dalend",
"nameFirstInsured": "Akkerman"
}
}
]
}
I want to convert this String as follows :
{
"productsList": [{
"productSubcategory": "Levensverzekering",
"nameFirstInsured": "Akkerman"
},
{
"productSubcategory": "Lineair dalend",
"nameFirstInsured": "Akkerman"
}
]
}
I have converted JSONArray to String so need operation as on the String on provided String in JSON format.
How I can change the String as required? What should I put in jsonString.replaceAll("","") function?
There is no easy way to do this, you have to do something like this.
OUTPUT IS:
{
"productsList":[
{
"productSubcategory":"Levensverzekering",
"nameFirstInsured":"Akkerman"
},
{
"productSubcategory":"Lineair dalend",
"nameFirstInsured":"Akkerman"
}
]
}
import java.io.FileReader;
import java.io.IOException;
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 IOException, InterruptedException {
JSONParser parser = new JSONParser();
JSONObject newObj = new JSONObject();
try {
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray arr = (JSONArray) jsonObject.get("productsList");
JSONArray newArr = new JSONArray();
for(int i = 0 ; i < arr.size();i++){
JSONObject object = (JSONObject) arr.get(i);
JSONObject a = (JSONObject) object.get("map");
newArr.add(a);
}
newObj.put("productsList", newArr);
System.out.println(newObj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have a text field where user can enter data, once data is received i want to append it to existing JSON file.
I am able to read the existing data and getting the text field value, but while appending the new data with existing data I'm facing problem.
Error:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 18 path $
Below code :
JSON File :
{"vins":[{"vin":"544554"},{"vin":"54554"}]}
Text field value : String test ="3689";
so it should be appended as :
{"vins":[{"vin":"544554"},{"vin":"54554"},{"vin":"3689"}]}
Filereadwrite class :
public class JSONFIlewrite {
public static String Vinno_Read;
public static List<String> linststring;
public static void main(String[] args) {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new
FileReader("C:\\Amaresh\\Test\\sample_json.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject);
linststring= new ArrayList();
// loop array
JSONArray msg = (JSONArray) jsonObject.get("vins");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
Vinno_Read = iterator.next().toString();
linststring.add(Vinno_Read);
}
String list_string = "";
System.out.println(linststring);
for(String temp:linststring){
list_string += temp;
System.out.println("amar1"+list_string);
}
System.out.println("amar"+list_string);
Vin vin4 = new Vin();
vin4.setVin("76354273462");
Vins vins = new Vins();
vins.addVins(vin4);
Gson gson = new Gson();
//String jsonValue=list_string;
String jsonValue = gson.toJson(list_string).toString();
System.out.println("json--"+jsonValue);
Vins vins1 = gson.fromJson(jsonValue, Vins.class);
System.out.println("ddd"+vins1);
Vin vin = new Vin();
vin.setVin("544554");
vins1.addVins(vin);
jsonValue = gson.toJson(vins1).toString();
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("C:\\Amaresh\\Test\\sample_json.json"));
writer.write(jsonValue);
System.out.println("Test"+jsonValue);
} catch (IOException e) {
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Setter Getter classes :
public class Vin {
#Expose
private String vin;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
}
public class Vins {
#Expose
List<Vin> vins = new ArrayList<>();
public List<Vin> getVins() {
return vins;
}
public void addVins(Vin vin) {
this.vins.add(vin);
}
}
Main Logic:
you can see 4 blocks in the code
Reading the json file and parsing to a java Object
Casting de java Object to a JSonObject, parsing to a JsonArray and iterating the array printing the JsonElements
Creating a new Vin Object and converting it to a JSON String using Gson.toJson method (2nd part is not required only illustrative purposes)
Creating a JsonWriter, creating a Vins Object and loading it with the original JsonArray and then adding a new element (that correspondents to the new Vin Object created in step #3, finally writing the Vins Object to the [new] file.
Input:
{"vins":[{"vin":"544554"},{"vin":"54554"}]}
Output:
{"vins":[{"vin":"544554"},{"vin":"54554"},{"vin":"3689"}]}
Code
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
public class JSONFIlewrite {
public static String Vinno_Read;
public static List<String> linststring;
public static void main(String[] args) {
try {
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader("C:\\Amaresh\\Test\\sample_json.json"));
JsonObject jsonObject = (JsonObject) obj;
System.out.println(jsonObject);
linststring = new ArrayList<String>();
// loop array
JsonArray msg = (JsonArray) jsonObject.get("vins");
Iterator<JsonElement> iterator = msg.iterator();
while (iterator.hasNext()) {
Vinno_Read = iterator.next().toString();
System.out.println("Vinno_Read---->" + Vinno_Read);
}
Vin newVin = new Vin();
newVin.setVin("3689");
Gson gson = new Gson();
String json = gson.toJson(newVin);
System.out.println("json---->" + json);
FileWriter file = new FileWriter("C:\\Amaresh\\Test\\sample_json2.json", false);
JsonWriter jw = new JsonWriter(file);
iterator = msg.iterator();
Vins vins = new Vins();
while (iterator.hasNext()) {
vins.addVin(gson.fromJson(iterator.next().toString(), Vin.class));
}
vins.addVin(newVin);
gson.toJson(vins, Vins.class, jw);
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Notes:
Since I don't know what library you are using, I have updated the class names to be compatible to GSON.
I have also changed the method: public void addVins(Vin vin) in Vins Class to public void addVin(Vin vin)
To keep the existing content and append the new content to the end of JSON file:
Example1:
new FileWriter(file,true);
or you can try example02:
FileWriter file= new FileWriter(JSONLPATH,true)
I have a large stream of data that I can capture from a game that I play using CharlesProxy. I'd like to parse the data and have it print out (eventually build an excel spreadsheet) the player names, x and y location, and the guild name.
The JSON data in Paste-Bin (you'll have to go down a few entries to see one of the results that actually returns a player name as well):
http://pastebin.com/v4kAaspn
Here's an example I found here that I tried to use to just return the player name, but I get a Null Pointer Exception error. Any advice will be greatly appreciated, thank you so much!
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ToolMain {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(
"//Users//Brandon//Desktop//JSONData.JSON"));
JSONObject jsonObject = (JSONObject) obj;
//get responses
JSONArray rsp = (JSONArray)jsonObject.get("responses");
//System.out.println(rsp);
//get return value
JSONObject rtvalue = (JSONObject)rsp.get(0);
//System.out.println(rtvalue);
//get hexes object
JSONObject hexes = (JSONObject)rtvalue.get("return_value");
//System.out.println(hexes);
//get hexes array
JSONArray hexesArray = (JSONArray)hexes.get("hexes");
Iterator<JSONObject> iterator = hexesArray.iterator();
while (iterator.hasNext()) {
JSONObject factObj = iterator.next();
String playerName = (String) factObj.get("player_name");
if (playerName != null) {
System.out.println(playerName);
}
}
//System.out.println(hexesArray);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
The NullPointerException is happening on below line because your JSONArray msg is null:
Iterator<JSONObject> iterator = msg.iterator();
Apply a check if(msg is not null) before you create an iterator on it.
Try it this way:
JSONObject jsonObject = (JSONObject) obj;
//get responses
JSONArray rsp = (JSONArray)jsonObject.get("responses");
System.out.println(rsp);
//get return value
JSONObject rtvalue = (JSONObject)rsp.get(0);
System.out.println(rtvalue);
//get hexes object
JSONObject hexes = (JSONObject)rtvalue.get("return_value");
System.out.println(hexes);
//get hexes array
JSONArray hexesArray = (JSONArray)hexes.get("hexes");
System.out.println(hexesArray);
i need to convert a POJO to a JSONObject (org.json.JSONObject)
I know how to convert it to a file:
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File(file.toString()), registrationData);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But I dont want a file this time.
If we are parsing all model classes of server in GSON format then this is a best way to convert java object to JSONObject.In below code SampleObject is a java object which gets converted to the JSONObject.
SampleObject mSampleObject = new SampleObject();
String jsonInString = new Gson().toJson(mSampleObject);
JSONObject mJSONObject = new JSONObject(jsonInString);
If it's not a too complex object, you can do it yourself, without any libraries. Here is an example how:
public class DemoObject {
private int mSomeInt;
private String mSomeString;
public DemoObject(int i, String s) {
mSomeInt = i;
mSomeString = s;
}
//... other stuff
public JSONObject toJSON() {
JSONObject jo = new JSONObject();
jo.put("integer", mSomeInt);
jo.put("string", mSomeString);
return jo;
}
}
In code:
DemoObject demo = new DemoObject(10, "string");
JSONObject jo = demo.toJSON();
Of course you can also use Google Gson for more complex stuff and a less cumbersome implementation if you don't mind the extra dependency.
The example below was pretty much lifted from mkyongs tutorial. Instead of saving to a file you can just use the String json as a json representation of your POJO.
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
YourObject obj = new YourOBject();
Gson gson = new Gson();
String json = gson.toJson(obj); //convert
System.out.println(json);
}
}
Here is an easy way to convert Java object to JSON Object (not Json String)
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.simple.parser.JSONParser;
JSONObject jsonObject = (JSONObject) JSONValue.parse(new ObjectMapper().writeValueAsString(JavaObject));
How to get JsonElement from Object:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
final ObjectMapper objectMapper = new ObjectMapper();
final Gson gson = new Gson();
String json = objectMapper.writeValueAsString(source);
JsonElement result = gson.fromJson(json, JsonElement.class);