Converting Java objects to JSON with Jackson

Converting Java objects to JSON with Jackson



I want my JSON to look like this:



"information": [
"timestamp": "xxxx",
"feature": "xxxx",
"ean": 1234,
"data": "xxxx"
,
"timestamp": "yyy",
"feature": "yyy",
"ean": 12345,
"data": "yyy"
]



Code so far:


import java.util.List;

public class ValueData

private List<ValueItems> information;

public ValueData()



public List<ValueItems> getInformation()
return information;


public void setInformation(List<ValueItems> information)
this.information = information;


@Override
public String toString()
return String.format("information:%s", information);





and


public class ValueItems

private String timestamp;
private String feature;
private int ean;
private String data;


public ValueItems()



public ValueItems(String timestamp, String feature, int ean, String data)
this.timestamp = timestamp;
this.feature = feature;
this.ean = ean;
this.data = data;


public String getTimestamp()
return timestamp;


public void setTimestamp(String timestamp)
this.timestamp = timestamp;


public String getFeature()
return feature;


public void setFeature(String feature)
this.feature = feature;


public int getEan()
return ean;


public void setEan(int ean)
this.ean = ean;


public String getData()
return data;


public void setData(String data)
this.data = data;


@Override
public String toString()
return String.format("timestamp:%s,feature:%s,ean:%s,data:%s", timestamp, feature, ean, data);




I just missing the part how I can convert the Java object to JSON with Jackson:


public static void main(String args)
// CONVERT THE JAVA OBJECT TO JSON HERE
System.out.println(json);



My Question is: Are my classes correct? Which instance do I have to call and how that I can achieve this JSON output?






The following tutorial might help: mkyong.com/java/how-to-convert-java-object-to-from-json-jackson

– maple_shaft
Apr 3 '13 at 11:33






Thanks that helped me :)

– JustTheAverageGirl
Apr 3 '13 at 13:16






if entity joined other tables then follow this way.. https://stackoverflow.com/questions/19928151/convert-entity-object-to-json/45695714#45695714

– Sedat Y
Aug 15 '17 at 15:13




8 Answers
8



To convert your object in JSON with Jackson:


object


ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);






OMG thank you. I've been looking for the .writer() all morning. Now if I can just find the documentation page for it I will be all set.

– RachelD
Apr 7 '14 at 19:44






Only thing is the String comes out escaped from the ObjectWriter. Use: new JSONObject(ow.writeValueAsString(msg)) if it's being sent out via Web Services like RESTful.

– jmarcosSF
Mar 23 '15 at 6:28







Out of interest why is it not os.writeValueAsJSONString(object)?

– DevilCode
Sep 8 '15 at 12:11






I'm facing this error, how to solve with your code No serializer found for class com.liveprocessor.LPClient.LPTransaction and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )

– user5268786
Jan 10 '16 at 14:38







libraries by the way : import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter;

– diego matos - keke
Apr 28 '16 at 16:34



I know this is old (and I am new to java), but I ran into the same problem. And the answers were not as clear to me as a newbie... so I thought I would add what I learned.



I used a third-party library to aid in the endeavor: org.codehaus.jackson
All of the downloads for this can be found here.


org.codehaus.jackson



For base JSON functionality, you need to add the following jars to your project's libraries:
jackson-mapper-asl
and
jackson-core-asl



Choose the version your project needs. (Typically you can go with the latest stable build).



Once they are imported in to your project's libraries, add the following import lines to your code:


import


import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;



With the java object defined and assigned values that you wish to convert to JSON and return as part of a RESTful web service


User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "sampleU@example.com";

ObjectMapper mapper = new ObjectMapper();

try
// convert user object to json string and return it
return mapper.writeValueAsString(u);

catch (JsonGenerationException | JsonMappingException e)
// catch various errors
e.printStackTrace();



The result should looks like this:
"firstName":"Sample","lastName":"User","email":"sampleU@example.com"


"firstName":"Sample","lastName":"User","email":"sampleU@example.com"






I believe the 'import' lines have changed to "import com.fasterxml.jackson.databind.ObjectMapper;"

– barrypicker
Feb 13 at 21:50



This might be useful:


objectMapper.writeValue(new File("c:\employee.json"), employee);

// display to console
Object json = objectMapper.readValue(
objectMapper.writeValueAsString(employee), Object.class);

System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(json));



just do this


Gson gson = new Gson();
return Response.ok(gson.toJson(yourClass)).build();






What is Response.ok ?

– Codeversed
Jun 16 '15 at 12:59






It's name of method

– Shell Scott
Jun 25 '15 at 20:45






I had a problem with JSON sizes inserted into mongoDB were above the allowed limit, when I turn on my Gson object has the larger size than with Jackson. Just a tip.

– Daniela Morais
Jun 30 '15 at 11:34






The question is about jackson, not Gson

– Ean V
Jan 21 '16 at 3:18


jackson


Gson






@Codeversed Response is a class in the Jersey library. Response.ok will return JSON response with status code 200.

– Pranav
Nov 10 '16 at 13:50



Well, even the accepted answer does not exactly output what op has asked for. It outputs the JSON string but with " characters escaped. So, although might be a little late, I am answering hopeing it will help people! Here is how I do it:


"


StringWriter writer = new StringWriter();
JsonGenerator jgen = new JsonFactory().createGenerator(writer);
jgen.setCodec(new ObjectMapper());
jgen.writeObject(object);
jgen.close();
System.out.println(writer.toString());



Note: To make the most voted solution work, attributes in the POJO have to be public or have a public getter/setter:


public


getter


setter



By default, Jackson 2 will only work with fields that are either
public, or have a public getter method – serializing an entity that
has all fields private or package private will fail.



Not tested yet, but I believe that this rule also applies for other JSON libs like google Gson.



You could do this:


String json = new ObjectMapper().writeValueAsString(yourObjectHere);


public class JSONConvector

public static String toJSON(Object object) throws JSONException, IllegalAccessException
String str = "";
Class c = object.getClass();
JSONObject jsonObject = new JSONObject();
for (Field field : c.getDeclaredFields())
field.setAccessible(true);
String name = field.getName();
String value = String.valueOf(field.get(object));
jsonObject.put(name, value);

System.out.println(jsonObject.toString());
return jsonObject.toString();



public static String toJSON(List list ) throws JSONException, IllegalAccessException
JSONArray jsonArray = new JSONArray();
for (Object i : list)
String jstr = toJSON(i);
JSONObject jsonObject = new JSONObject(jstr);
jsonArray.put(jsonArray);

return jsonArray.toString();







Too much work, too much reflection! Mappers are supposed to free you of doing these boilerplate stuff!

– Ean V
Jan 21 '16 at 3:16







I love Convectors!

– Christos
Oct 21 '16 at 16:55



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)