I created a simple POJO:
public class LoginPojo {
private String login_request = null;
private String email = null;
private String password = null;
// getters, setters
}
After some searching I found this: JSONObject jsonObj = new JSONObject( loginPojo );
But with this I got the error:
The constructor JSONObject(LoginPojo) is undefined
I found another solution:
JSONObject loginJson = new JSONObject();
loginJson.append(loginPojo);
But this method does not exist.
So how can I convert my POJO into a JSON?
Simply use the java Gson API:
Gson gson = new GsonBuilder().create();
String json = gson.toJson(obj);// obj is your object
And then you can create a JSONObject from this json String, like this:
JSONObject jsonObj = new JSONObject(json);
Take a look at Gson user guide and this SIMPLE GSON EXAMPLE for more information.
It is possible to get a (gson) JsonObject from POJO:
JsonElement element = gson.toJsonTree(userNested);
JsonObject object = element.getAsJsonObject();
After that you can take object.entrySet() and look up all the tree.
It is the only absolutely free way in GSON to set dynamically what fields you want to see.
Jackson provides JSON parser/JSON generator as foundational building block; and adds a powerful Databinder (JSON<->POJO) and Tree Model as optional add-on blocks. This means that you can read and write JSON either as stream of tokens (Streaming API), as Plain Old Java Objects (POJOs, databind) or as Trees (Tree Model). for more reference
You have to add jackson-core-asl-x.x.x.jar, jackson-mapper-asl-x.x.x.jar libraries to configure Jackson in your project.
Modified Code :
LoginPojo loginPojo = new LoginPojo();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
// Setting values to POJO
loginPojo.setEmail("a#a.com");
loginPojo.setLogin_request("abc");
loginPojo.setPassword("abc");
// Convert user object to json string
String jsonString = mapper.writeValueAsString(loginPojo);
// Display to console
System.out.println(jsonString);
} catch (JsonGenerationException e){
e.printStackTrace();
} catch (JsonMappingException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
Output :
{"login_request":"abc","email":"a#a.com","password":"abc"}
JSONObject input = new JSONObject(pojo);
This worked with latest version.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
You can also use project lombok with Gson overriding toString function. It automatically includes builders, getters and setters in order to ease the data assignment like this:
User user = User.builder().username("test").password("test").build();
Find below the example class:
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.google.gson.Gson;
#Data
#Builder(toBuilder = true)
#AllArgsConstructor
#NoArgsConstructor
public class User {
/* User name. */
private String username;
/* Password. */
private String password;
#Override
public String toString() {
return new Gson().toJson(this, User.class);
}
public static User fromJSON(String json) {
return new Gson().fromJson(json, User.class);
}
}
Simply you can use the below solution:
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(loginPojo);
JSONObject jsonObject = new JSONObject(str);
I use jackson in my project, but I think that u need a empty constructor.
public LoginPojo(){
}
You can use
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
To create a JSON object:
#Test
public void whenGenerateJson_thanGenerationCorrect() throws ParseException {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 2; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("AGE", 10);
jsonObject.put("FULL NAME", "Doe " + i);
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
jsonArray.add(jsonObject);
}
String jsonOutput = jsonArray.toJSONString();
}
Add the annotations to your POJO class like so:
#JSONField(name = "DATE OF BIRTH")
private String dateOfBirth;
etc...
Then you can simply use:
#Test
public void whenJson_thanConvertToObjectCorrect() {
Person person = new Person(20, "John", "Doe", new Date());
String jsonObject = JSON.toJSONString(person);
Person newPerson = JSON.parseObject(jsonObject, Person.class);
assertEquals(newPerson.getAge(), 0); // if we set serialize to false
assertEquals(newPerson.getFullName(), listOfPersons.get(0).getFullName());
}
You can find a more complete tutorial on the following site:
https://www.baeldung.com/fastjson
Related
I have an Object array which is a list of argument values a function could take. This could be any complex object.
I am trying to build a json out of the Object array using gson as below:
private JsonArray createArgsJsonArray(Object... argVals) {
JsonArray argsArray = new JsonArray();
Arrays.stream(argVals).forEach(arg -> argsArray.add(gson.toJson(arg)));
return argsArray;
}
This treats all the arg values as String.
It escapes the String args
"args":["\"STRING\"","1251996697","85"]
I prefer the following output:
"args":["STRING",1251996697,85]
Is there a way to achieve this using gson?
I used org.json, I was able to achieve the desired result, but it does not work for complex objects.
EDIT:
I applied the solution provided by #MichaĆ Ziober, but now how do I get back the object.
Gson gson = new Gson();
Object strObj = "'";
JsonObject fnObj = new JsonObject();
JsonObject fnObj2 = new JsonObject();
fnObj.add("response", gson.toJsonTree(strObj));
fnObj2.addProperty("response", gson.toJson(strObj));
System.out.println(gson.fromJson(fnObj.toString(),
Object.class)); --> prints {response='} //Not what I want!
System.out.println(gson.fromJson(fnObj2.toString(),
Object.class)); --> prints {response="\u0027"}
Use toJsonTree method:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import java.util.Date;
public class GsonApp {
public static void main(String[] args) {
GsonApp app = new GsonApp();
System.out.println(app.createArgsJsonArray("text", 1, 12.2D));
System.out.println(app.createArgsJsonArray(new Date(), new A(), new String[] {"A", "B"}));
}
private Gson gson = new GsonBuilder().create();
private JsonArray createArgsJsonArray(Object... argVals) {
JsonArray argsArray = new JsonArray();
for (Object arg : argVals) {
argsArray.add(gson.toJsonTree(arg));
}
return argsArray;
}
}
class A {
private int id = 12;
}
Above code prints:
["text",1,12.2]
["Sep 19, 2019 3:25:20 PM",{"id":12},["A","B"]]
If you want to end up with a String, just do:
private String createArgsJsonArray(Object... argVals) {
Gson gson = new Gson();
return gson.toJson(argVals);
}
If you wish to collect it back and alter just do:
Object[] o = new Gson().fromJson(argValsStr, Object[].class);
Try using setPrettyPrinting with DisableHtml escaping.
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonArray.toString());
System.out.println( gson.toJson(je));
I know this question or similar ones have been asked multiple times here, but I swear I've read tons of related posts and none of the solutions seems to be working for me.
I'm trying to map some JSON data, which I receive from a specific REST API, to a Java class. The JSON has this format:
{"netStatLinks":[
{"src":"of:0000000000000002/3",
"dst":"of:0000000000000000/1",
"bw":10000.0,
"rate":0.0,
"usage":0.0,
"available":10000.0},
{"src":"of:0000000000000005/3",
"dst":"of:0000000000000006/1",
"bw":10000.0,
"rate":0.0,
"usage":0.0,
"available":10000.0},
{...and so on}
]}
The Java class I want to map the JSON to is this:
public class NetStatLinkList {
private List<NetStatLink> netStatLinks;
// Generated getter and setter
#Override
public String toString(){
return netStatLinks.toString();
}
}
and
public class NetStatLink {
public String src;
public String dst;
public double bw;
public double rate;
public double usage;
public double available;
public NetStatLink(String src, String dst, double bw, double rate, double usage, double available){
this.src = src;
this.dst = dst;
this.bw = bw;
this.rate = rate;
this.usage = usage;
this.available = available;
}
// Generated getters and setters
#Override
public String toString() {
return "Link "+src +"to"+ dst+" -- "+"rate: "+rate;
}
}
I can read the JSON correctly but I can't manage to map it in any way. I've tried all this options without success (note that url is an URL object created based on the url string and that all the neccessary exceptions are implicitly catched):
Using Jackson to directly map the JSON to NetStatLinkList
ObjectMapper mapper = new ObjectMapper();
NetStatLinkList linkLst = mapper.readValue(url,NetStatLinkList.class);
Using Jackson to map the JSON to a List of NetStatLink objects
TypeReference<List<NetStatLink>> type = new TypeReference<List<NetStatLink>>() {};
List<NetStatLink> linkLst = mapper.readValue(url, mapType);
Using Jackson to map the JSON string directly to the class/to a List of objects
JsonNode rootNode = mapper.readValue(url,JsonNode.class);
JsonNode data = rootNode.get("netStatLinks");
List<NetStatLink> linkLst = mapper.readValue(data.toString(), mapType);
// or
NetStatLink[] linkLst = mapper.readValue(data.toString(), NetStatLink[].class)
// or
List<NetStatLink> linkLst = mapper.readValue(data.traverse(), mapType);
Using Jackson to map the JSON to an ArrayNode and iterate through it
JsonNode linkData = mapper.readTree(url);
ArrayNode linkDataArray = (ArrayNode)linkData.get("netStatLinks");
List<NetStatLink> linkLst;
while(linkDataArray.elements().hasNext()){
linkLst.add(mapper.readValue(linkDataArray.elements().next().toString(),NetStatLink.class));
}
Using the external library json-simple to read the JSON and then map it with Jackson
String location = IOUtils.toString(url);
JSONObject jo = (JSONObject) JSONValue.parseWithException(location);
JSONArray val = (JSONArray) jo.get("NetStatLinks");
List<NetStatLink> linkLst = mapper.readValue(val.toJSONString(), mapType);
// or
NetStatLink[] linksList = mapper.readValue(val.toJSONString(), NetStatLink[].class);
Do you know if there's any other way I could map this JSON data to my classes, or if there's any mistake in those methods which is the reason I cannot get them to work?
You can use gson
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.1</version>
</dependency>
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("netStatLinks");
List<NetStatLink> users = new ArrayList<NetStatLink>();
Gson gson = new Gson();
Type listType = new TypeToken<List<NetStatLink>>(){}.getType();
netStatLink = gson.fromJson(jsonArr ,listType);
I'm getting a JSON array in string like
[ { "id":"ca.Primary_Diagnosis_Dt",
"field":"ca.Primary_Diagnosis_Dt",
"type":"date",
"input":"text",
"operator":"not_equal",
"value":"2016/06/07"
},
{ "id":"ca.Clinical_Stage",
"field":"ca.Clinical_Stage",
"type":"integer",
"input":"select",
"operator":"equal",
"value":"I"
}
]
i just want to save the value of id ,operator and value in LIST please help
Online : Working code
First create a class to store your values :
class Data{
String id;
String operator;
String value;
}
Then iterate over the json :
JSONArray jsonArr = new JSONArray("[JSON Stirng]");
List<Data> dataList = new ArrayList<>();
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
Data data = new Data();
data.id = jsonObj.getString("id");
data.operator = jsonObj.getString("operator");
data.value = jsonObj.getString("value");
dataList.add(data);
}
Now dataList has your data!
P.S. : Use getter/setters in Data class
JAR : http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm
Use any JSON parsor eg: GSON to create an arraylist of this particular json
Iterate the arraylist
Save it :)
You can do that with a JSon library such as org.glassfish.javax.json
In Maven use
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
</dependency>
Then read the string to a JsonArray:
JsonArray ja = Json.createReader(new StringReader(input)).readArray();
Then iterate over the list, map the objects to a new objects with just the values you need:
List<JsonObject> list = ja.stream()
.map(o -> (JsonObject) o)
.map(jo -> Json.createObjectBuilder()
.add("id", jo.getJsonString("id"))
.add("operator", jo.getJsonString("operator"))
.add("value", jo.getJsonString("value")).build())
.collect(Collectors.toList());
In case you could not use JsonObject as output, you may use a value object instead - just like Himanshu Tyagi proposed - and map the values to that object.
In your case, I think, the JSON should be parsed into a List<Map<String,String>>. This can be done using Jackson. Following is a method that converts a JSON string into List<Map<String,String>>:
public static List<Map<String, String>> toList(String json) throws IOException {
List<Map<String, String>> listObj;
ObjectMapper MAPPER = new ObjectMapper();
listObj = MAPPER.readValue(json, new TypeReference<ArrayList<HashMap<String, String>>>() {
});
return listObj;
}
If you have created a POJO class for it then you can use:
public static List<PojoClass> toList(String json) throws IOException {
List<PojoClass> listObj;
ObjectMapper MAPPER = new ObjectMapper();
listObj = MAPPER.readValue(json, new TypeReference<ArrayList<PojoClass>>() {
});
return listObj;
}
Maven dependency for Jackson:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
I have a problem at hand..
public class SomeClass{
List<Template> templateSettings;
}
public class Template{
String id;
List<TemplateChild> child;
}
public class TemplateChild{
String id;
String something;
}
at the ajax level i have
#ajax
public class saveSettings(SomeClass someclass){
List<Template> templateSettings = someclass.getTemplateSettings();
}
Its a bit complex , can someone help me in constructing the JSON for this, i am very new to javascript.. thanks..
Gson library will do that for you, Its pretty simple to use, here is the link
You can simply download the jar file and create the object like this
{ Gson gson = new Gson();
String convertedJson = gson.toJson(yourobject);}
And you are done.
Your JSON should look like
templetSettings= [{
template = {id="someId", childs=[{id="someId", something="something"},{id="someId2", something="something2"}]}},{
template = {//same as above},{
template = {//same as above}
]
Use JSONObject and JSONArray to create this kind of structure. Its pretty easy to use really
JSONArray templateSettings = new JSONArray();
for(//configure loop accordigly) {
JSONObject template = new JSONObject();
JSONArray childs = new JSONArray();
for (//Configure accordingly) {
JSONObject child = new JSONObject;
child.put("id", "someId");
child.put("something", "something");
childs.add(child);
}
template.put("id", "someId");
template.put("childs", childs);
templateSettings.add(template);
}
After this you only need to do is
out.write(templateSettings.toString());
And you are done
To do this on javaScript side loop accordingly and take help from this example
http://jsfiddle.net/AMISingh/636vN/
I want the following json ,where List<form> will have list of form_id,form_name, how can I convert this using jsonobject, I am not getting the proper json output. Please help me with this.
Json:
{
"forms": [
{ "form_id": "1", "form_name": "test1" },
{ "form_id": "2", "form_name": "test2" }
]
}
The above is the json structure that i need it for a list.Where id ,name is a list from form object
public static JSONObject getJsonFromMyFormObject(List<Form> form) {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = null;
System.out.println(form.size());
for (int i = 0; i < form.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("form", jsonArray);
return responseDetailsJson;
}
Facing issue here not getting output as a list
The code in the original question is close to achieving the described desired result. Just move the JSONArray instance creation outside of the loop.
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Foo
{
public static JSONObject getJsonFromMyFormObject(List<Form> form)
{
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < form.size(); i++)
{
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);
return responseDetailsJson;
}
public static void main(String[] args)
{
List<Form> forms = new ArrayList<Form>();
forms.add(new Form("1", "test1"));
forms.add(new Form("2", "test2"));
JSONObject jsonObject = getJsonFromMyFormObject(forms);
System.out.println(jsonObject);
}
}
class Form
{
String id;
String name;
Form(String i, String n)
{
id = i;
name = n;
}
String getId()
{
return id;
}
String getName()
{
return name;
}
}
Properbly http://www.roseindia.net/tutorials/json/jsonobject-java-example.shtml will help.
According the comment from Tushar, here the extract from the aboved linked website:
Now in this part you will study how to use JSON in Java.
To have functionality of JSON in java you must have JSON-lib. JSON-lib also
requires following "JAR" files:
commons-lang.jar
commons-beanutils.jar
commons-collections.jar
commons-logging.jar
ezmorph.jar
json-lib-2.2.2-jdk15.jar
JSON-lib is a java library for that transforms beans, collections, maps, java arrays and XML to JSON and
then for retransforming them back to beans, collections, maps and
others. In this example we are going to use JSONObject class for
creating an object of JSONObject and then we will print these object
value. For using JSONObject class we have to import following package
"net.sf.json". To add elements in this object we have used put()
method. Here is the full example code of FirstJSONJava.java is as
follows:
FirstJSONJava.java
import net.sf.json.JSONObject;
public class FirstJSONJava
{
public static void main(String args[])
{
JSONObject object=new JSONObject();
object.put("name","Amit Kumar");
object.put("Max.Marks",new Integer(100));
object.put("Min.Marks",new Double(40));
object.put("Scored",new Double(66.67));
object.put("nickname","Amit");
System.out.println(object);
}
}
To run this example you have to follow these few steps as follows:
Download JSON-lib jar and other supporting Jars
Add these jars to your classpath
Create and save FirstJSONJava.java
Compile it and execute it.