Jackson JSON Mapper library for string

I have a class ( A and B are my objects)

 public A { private List<B> b; private int c; } 

I have a temp String variable. Therefore, I would save the JSON string of my object in this variable. How?

I tried this method 2, but with no result.

 public void save() { ObjectMapper mapper = new ObjectMapper(); String temp = mapper.writeValueAsString(a); } public void read(String temp) { ObjectMapper mapper = new ObjectMapper(); A a = mapper.readValue(temp, A.class); } 

How can I solve it?

+7
source share
1 answer

The code should pass an instance of type A to the writeValueAsString method writeValueAsString not the actual class.

ObjectMapper will be able to determine the type of instance through reflection, however, if you do not pass the instance, it will not be able to determine the value of the field to be placed in the generated JSON.

Also be sure to catch or throw the appropriate exceptions.

 public void save() { try { A a = new A(); ObjectMapper mapper = new ObjectMapper(); String temp = mapper.writeValueAsString(a); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } 

You must also have descriptors for fields of class A and class B NOTICE I included B in the previous sentence, since Jackson should be able to display all the fields in the instance that we provide him.

 public A { private List<B> b; private int c; private B getB(){ return b;} private void setB(B b){this.b = b;} private int getC(){return c;} private void setC(int c){this.c = c;} } 

Here is a complete working example that I tested.

 import java.io.IOException; import java.util.List; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class A { private List<B> b; private int c; public List<B> getB() { return b; } public void setB(List<B> b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException { A a = new A(); ObjectMapper mapper = new ObjectMapper(); String temp = mapper.writeValueAsString(a); System.out.println(temp); } } class B{ } 

If this simple example does not work, the jackson-mapper-asl.jar is most likely not in the build path. Download the file from here and place it somewhere on your local computer.

Next, through Eclipse, right-click on your project and select properties.

Then choose Build Path> Libraries> Add External Banks. Find the jar and click "OK."

+12
source

All Articles