How to convert a Java Object to a JSONObject? - java

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

Related

Converting Map to JSON in Java

I am having a map
Map<String, Application.RiskFactor> appRiskFactorsMap = app.getRiskFactors();
It has this data kind of in it
{risk1=Application.RiskFactor(risk=risk1, question=question1,
factor=true), risk2=Application.RiskFactor(risk=risk2,
question=question2?, factor=true),
risk3=Application.RiskFactor(risk=risk3, question=question3?,
factor=true)}
I am converting it into JSON and having this output.
{"risk1":{"risk":"risk1","question":"question1?","factor":"true"},"":
{"risk":"risk2","question":"question2?","factor":"true"},"risk3":
{"risk":"risk3","question":"question3?","factor":"true"}}
I have this JSON converter class
package system.referee.util;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public final class JsonUtils {
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
// Ignore unknown fields while deserialization
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// Ignore null & Optional.EMPTY fields while serialization
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
}
public static <T> String toJson(T obj) {
try {
return MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
return "";
}
}
public static <T> T fromJson(String json, Class<T> type) {
try {
return MAPPER.readValue(json, type);
} catch (JsonProcessingException e) {
return null;
}
}
}
I want to print the JSON in this format
{"risk":"risk1","question":"question1?","factor":"true"},
{"risk":"risk2","question":"question2?","factor":"true"},
{"risk":"risk3","question":"question3?","factor":"true"}
is there any way to achieve that? I am unable to find any help with this. thanks a lot
You should ignore keys and serialise only values:
JsonUtils.toJson(appRiskFactorsMap.values())
Result will be a JSON Array.

Append text field data to an existing JSON file in java

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)

How to change JsonObject in JsonArray?

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

parse json java result null

I am stucking with parse json in java. Here is my code:
package url.process;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class jsonArray implements JSONAware{
private long l;
public jsonArray(long l){
this.l=l;
}
public long getArray(){
return l;
}
public void setArray(long l){this.l=l;}
#Override
public String toJSONString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("\""+getArray()+"\"");
sb.append("}");
return sb.toString();
}
public static void main(String[] args){
// doc doi tuong thanh chuoi
List <jsonArray> listjsonarray = new ArrayList<jsonArray>(){
{
add( new jsonArray(76543456));
add( new jsonArray(112233445));
add( new jsonArray(546372));
add( new jsonArray(9876553));
}
};
System.out.println(JSONArray.toJSONString(listjsonarray));
//doc chuoi thanh doi tuong
String jsonString = "[{\"76543456\"},"+"{\"112233445\"},"+"{\"546372\"},"+"{\"9876553\"}]";
try{
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonString);
for(int i =0;i<jsonArray.size();i++){
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
long l = Long.parseLong((String) jsonObject.get("l"));
jsonArray ja = new jsonArray(l);
System.out.println("Elements is "+ja.getArray());
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
The result is :
[{"76543456"},{"112233445"},{"546372"},{"9876553"}]
null
I do not know to parse this array above. Please help me, thank you so much and have a good time.
The null output is because of
}catch(Exception e){
System.out.println(e.getMessage());
});
The json is not valid and therefore you get a ParseException and this exception has no message.
As I can see you want to get the l property of the JSONObject
long l = Long.parseLong((String) jsonObject.get("l"));
in this case the correct json would be
String jsonString = "[{\"l\": \"76543456\"},"+"{\"l\": \"112233445\"},"+"{\"l\": \"546372\"},"+"{\"l\": \"9876553\"}]";
Your JSON is invalid. Braces {} indicate a JSON object which contains key-value pairs. But you are putting JSON strings in them.
[{"76543456"},{"112233445"},{"546372"},{"9876553"}]
Perhaps you meant to have
["76543456","112233445","546372","9876553"]
The JSON format is described here.
You'll have other problems later when trying to cast a String to a JSONObject. Handle those appropriately. If you're storing JSON strings, you should get back Java String objects.
JSON is a key value data structure. For example, a JSON object is as follow:
{"name" : "John Smith"}
The string you input there doesn't follow the convention of JSON, therefore the program couldn't work

java.lang.String cannot be cast to org.json.simple.JSONObject simple-json

I am getting strange problem while trying to parse a simple json using simple-json by google.
Here is my code which is not working:
String s = args[0].toString();
JSONObject json = (JSONObject)new JSONParser().parse(s);
When I execute, it will give me the exception java.lang.String cannot be cast to org.json.simple.JSONObject
But when I hard code json directly like below its working fine. Wat could be the reason?
JSONObject json = (JSONObject)new JSONParser().parse("{\"application\":\"admin\",\"keytype\":\"PRODUCTION\",\"callbackUrl\":\"qwerewqr;ewqrwerq;qwerqwerq\",\"authorizedDomains\":\"ALL\",\"validityTime\":\"3600000\",\"retryAfterFailure\":true}");
UPDATE
When I print s, it will give me the output below:
"{\"application\":\"admin\",\"keytype\":\"PRODUCTION\",\"callbackUrl\":\"qwerewqr;ewqrwerq;qwerqwerq\",\"authorizedDomains\":\"ALL\",\"validityTime\":\"3600000\",\"retryAfterFailure\":true}"
I ran this through eclipse by providing arguments in run configuration.
public static void main(String[] args) {
String s = args[0].toString();
System.out.println("=>" + s);
try {
JSONObject json = (JSONObject) new JSONParser().parse(s);
System.out.println(json);
} catch (ParseException e) {
e.printStackTrace();
}
}
Output
=>{"application":"admin","keytype":"PRODUCTION","callbackUrl":"qwerewqr;ewqrwerq;qwerqwerq","authorizedDomains":"ALL","validityTime":"3600000","retryAfterFailure":true}
{"validityTime":"3600000","callbackUrl":"qwerewqr;ewqrwerq;qwerqwerq","application":"admin","retryAfterFailure":true,"authorizedDomains":"ALL","keytype":"PRODUCTION"}
Make sure that the string is a valid JSON. You can user JSONObject parameterized constructor with the given string to convert the JSON string to a valid JSON object.
For example,
try {
String jsonString = " {'application':'admin','keytype':'PRODUCTION','callbackUrl':'qwerewqr;ewqrwerq;qwerqwerq','authorizedDomains':'ALL','validityTime':3600000,'retryAfterFailure':true}";
JSONObject data = new JSONObject(jsonString);
String application = data.getString("application"); //gives admin
String keytype = data.getString("keytype"); //gives PRODUCTION
} catch (JSONException e) {
e.printStackTrace();
}
I had the same issue
package com.test;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JSONTest {
public static void main(String[] args) {
String s = args[0];
try {
JSONObject json = new JSONObject((String) new JSONParser().parse(s));
System.out.println(json);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
This worked for me
Try this
package com.test;
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[] args) {
String s = args[0];
try {
JSONObject json = (JSONObject) new JSONParser().parse(s);
System.out.println(json);
} catch (ParseException e) {
e.printStackTrace();
}
}
Then on command line
java -classpath ".;json-simple-1.1.1.jar" com.test.JSONTest {\"application\":\"admin\",\"keytype\":\"PRODUCTION\",\"callbackUrl\":\"qwerewqr;ewqrwerq;qwerqwerq\",\"authorizedDomains\":\"ALL\",\"validityTime\":\"3600000\",\"retryAfterFailure\":true}
The out put is
{"validityTime":"3600000","callbackUrl":"qwerewqr;ewqrwerq;qwerqwerq","application":"admin","retryAfterFailure":true,"authorizedDomains":"ALL","keytype":"PRODUCTION"}

Categories