Basic JavaBean we use:

public class AccountBean {
    private int id;
    private String name;
    private String email;
    private String address;
    private Birthday birthday;
    
    //getter、setter
    
    @Override
    public String toString() {
        return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
    }
}

 
public class Birthday {
    private String birthday;
    
    public Birthday(String birthday) {
        super();
        this.birthday = birthday;
    }
 
    //getter、setter
 
    public Birthday() {}
    
    @Override
    public String toString() {
        return this.birthday;
    }
} 

test class:

public class JacksonTest {
    private JsonGenerator jsonGenerator = null;
    private ObjectMapper objectMapper = null;
    private AccountBean bean = null;
    
    @Before
    public void init() {
        bean = new AccountBean();
        bean.setAddress("china");
        bean.setEmail("abc@gmail.com");
        bean.setId(1);
        bean.setName("jamie");
        
        objectMapper = new ObjectMapper();
        try {
            jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @After
    public void destory() {
        try {
            if (jsonGenerator != null) {
                jsonGenerator.flush();
            }
            if (!jsonGenerator.isClosed()) {
                jsonGenerator.close();
            }
            jsonGenerator = null;
            objectMapper = null;
            bean = null;
            System.gc();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} 

1. Java Object to JSON

@Test
public void writeEntityJSON() {
    
    try {
        System.out.println("jsonGenerator");
        // writeObject can convert java objects,eg:JavaBean/Map/List/Array, etc.
        jsonGenerator.writeObject(bean);    
        System.out.println();
        
        System.out.println("ObjectMapper");
        // writeValue has simlar function with writeObject
        objectMapper.writeValue(System.out, bean);
    } catch (IOException e) {
        e.printStackTrace();
    }
} 
Output:
jsonGenerator
{"address":"china","name":"jamie","id":1,"birthday":null,"email":"abc@gmail.com"}
ObjectMapper
{"address":"china","name":"jamie","id":1,"birthday":null,"email":"abc@gmail.com"} 

Above the use of JsonGenerator writeObject method and ObjectMapper writeValue method to complete the conversion of Java objects, the two pass the parameters and constructed in a different way; JsonGenerator depends on the creation of ObjectMapper. That is to say, if you want to use JsonGenerator to convert JSON, then you must create an ObjectMapper, but you use ObjectMapper to convert JSON, you do not need JSONGenerator.

objectMapper writeValue method can convert a Java object into JSON. This method’s first parameter need to be an output stream. After the conversion, it can be outputed through this stream. Or provide a File to write the converted content to the File. Of course, this parameter can also receive a JSONGenerator, and then through the JSONGenerator to output the converted information. The second parameter is the Java object that will be converted. If you use the three-argument method, then it is a config, which can provide some rules for conversion, filtering or converting certain properties of the specified Java object, and so on.

2. Map to JSON

@Test
public void writeMapJSON() {
    try {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", bean.getName());
        map.put("account", bean);
        bean = new AccountBean();
        bean.setAddress("china-Beijin");
        bean.setEmail("hoojo@qq.com");
        map.put("account2", bean);
        
        System.out.println("jsonGenerator");
        jsonGenerator.writeObject(map);
        System.out.println("");
        
        System.out.println("objectMapper");
        objectMapper.writeValue(System.out, map);
    } catch (IOException e) {
        e.printStackTrace();
    }
} 

3. List to JSON

@Test
public void writeListJSON() {
    try {
        List<AccountBean> list = new ArrayList<AccountBean>();
        list.add(bean);
        
        bean = new AccountBean();
        bean.setId(2);
        bean.setAddress("address2");
        bean.setEmail("email2");
        bean.setName("haha2");
        list.add(bean);
        
        System.out.println("jsonGenerator");
        // list to JSON string
        jsonGenerator.writeObject(list);
        System.out.println();
        System.out.println("ObjectMapper");
        // objectMapper direct get json string converted from the list
        System.out.println("1###" + objectMapper.writeValueAsString(list));
        System.out.print("2###");
        // objectMapper convert list to JSON string
        objectMapper.writeValue(System.out, list);
    } catch (IOException e) {
        e.printStackTrace();
    }
} 

4. Json to Java Object

@Test
public void readJson2Entity() {
    String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
    try {
        AccountBean acc = objectMapper.readValue(json, AccountBean.class);
        System.out.println(acc.getName());
        System.out.println(acc);
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
} 

5. Json to List

@Test
public void readJson2List() {
    String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
                "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
    try {
        List<LinkedHashMap<String, Object>> list = objectMapper.readValue(json, List.class);
        System.out.println(list.size());
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            Set<String> set = map.keySet();
            for (Iterator<String> it = set.iterator();it.hasNext();) {
                String key = it.next();
                System.out.println(key + ":" + map.get(key));
            }
        }
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
} 

I tried converting the above JSON to List and then the List holds the AccountBean but it failed. But Map collections are supported. Because the programme will be converted from JSON to List.class, but do not know what type of storage within the List, had to default to Map type, because all objects can be converted to Map combination.

6. Json to Array

Since the above generic conversion does not recognise the type of the object in the collection. So here the problem is solved with an Array  object. Only it is no longer a collection, but an array. Of course this doesn’t matter, you can just use Arrays.asList() to convert it to a List type.

@Test
public void readJson2Array() {
    String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
            "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
    try {
        AccountBean[] arr = objectMapper.readValue(json, AccountBean[].class);
        System.out.println(arr.length);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
        
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
} 

7. Json to Map

@Test
public void readJson2Map() {
    String json = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
                "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
    try {
        Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
        System.out.println(maps.size());
        Set<String> key = maps.keySet();
        Iterator<String> iter = key.iterator();
        while (iter.hasNext()) {
            String field = iter.next();
            System.out.println(field + ":" + maps.get(field));
        }
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
} 

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

Catalogue