Converting Java Objects to JSON with Jackson

Converting Java objects to JSON with Jackson

To convert your object in JSON with Jackson:

import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.ObjectWriter;

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

Converting JSON to a java object using Jackson

You are right it is because of the [] on the JSON response. This means that the JSON object that is being returned is an array of objects.

Hence to get Jackson to map it correctly you should be doing this:

LightswitchResponse[] lightswitchResponses = 
mapper.readValue(response.toString(), LightswitchResponse[].class);

You can then read the first element off this to get your desired LightSwitchResponse object:

LightswitchResponse lightswitchResponse = lightswitchResponses[0];

Convert Java object to json string containing a json string property already

I managed to overcome this problem by using @JsonRawValue

From documentation https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonRawValue.html it states the following:

Marker annotation that indicates that the annotated method or field should be serialized by including literal String value of the property as is, without quoting of characters. This can be useful for injecting values already serialized in JSON or passing javascript function definitions from server to a javascript client.
Warning: the resulting JSON stream may be invalid depending on your input value.

So by doing,

import com.fasterxml.jackson.annotation.JsonRawValue;
....
class User {

String name;

int age;

@JsonRawValue
String locationJson; // this is a json already

//allArgsConstructor, getters & setters
}

I kinda told Jackson that this is a json value already don't do your job here
so same code in post generated the correct json

{
"name": "Max",
"age": "13",
"locationJson": {"latitude":30.0000, "longitude":32.0000}
}

Convert Java objects to JSON with specific fields

Consider writing two separate wrapper classes which each expose the fields you want for the two cases, and pass the pojo as a constructor arg.

So, one of them exposes one set of properties and might look like this:

public class JsonObject1 {
private MyPojo myPojo;
public JsonObject1(MyPojo myPojo) {
this.myPojo = myPojo;
}

public void getProperty1() {
return myPojo.getProperty1();
}
......
}

and the other is similar, but exposes the other subset of properties.

Alternatively, you could add two methods (possibly to your POJO, or possibly to a service class that is exposing the POJO) that each returns a Map (eg a HashMap) where you've copied across the specific properties you want for each view, and then convert those Maps to JSON. This is less "model-driven", but might be less work overall. Thanks to @fvu for this observation!

public Map<String, Object> getPojoAsMap1() {
Map<String, Object> m = new HashMap<>();
m.put("property1", pojo.getProperty1());
....
return m;
}

It's also possible that the two different JSON representations are trying to tell you that your POJO should be split up into two POJOs - sometimes things like this are hints about how your code could be improved. But it depends on the circumstances, and it might not apply in this case.

How to convert a Java Object to a JSONObject?

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.

Convert nested java objects to Jackson JSON

Create a class Address.

public class Address {
private String street;
private String city;
private int zip;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
}

Create a class Id.

 public class Id {
private String fname;
private String lname;
private Address addr;
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public Address getAddr() {
return addr;
}
public void setAddr(Address addr) {
this.addr = addr;
}
}

Main method:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {
public static void main(String[] args) {
Address addressObj = new Address();
addressObj.setCity("Chicago");
addressObj.setStreet("Some Street");
addressObj.setZip(12345);

Id idObj = new Id();
idObj.setAddr(addressObj);
idObj.setFname("Test");
idObj.setLname("Tester");

ObjectMapper mapper = new ObjectMapper();

//Object to JSON in String
try {
String jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(idObj);
System.out.println(jsonInString);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Output:

{
"fname" : "Test",
"lname" : "Tester",
"addr" : {
"street" : "Some Street",
"city" : "Chicago",
"zip" : 12345
}
}


Related Topics



Leave a reply



Submit