Method of converting object to json

foreword

JSON and XML are used in formats that can be used for data transmission between networks. They are relatively lightweight, similar to a transmission protocol, and can be parsed by js. There is also an object stream transmission method between networks, but the conditions agreed between the transmitters are more.

The main format of json is {"key":"value","key":"value"}. When javabean overrides the toString() method of Object, the return result is also in json format. So how to convert an object into a json string.

There are several ways:

1. Non-collection types.

(1) toString() method. For non-collection types, the overridden toString method suffices. Of course, the class cannot have a collection type inside either. Of course, if all classes in the project rewrite the toString method, it is also possible to have a collection, so the specification requirements for the project are relatively high.

(2) Use JsonObject and JsonArray classes, for standard pojo classes (javaBean), use JSONArray sub = JSONArray.fromObject(object), and then call the json.toString() method.

2. For collection classes

(1) Use JsonObject and JsonArray classes (from org.json.JSONArray and org.json.JSONObject

            List<Article> al = articleMng.find(f);
            System.out.println(al.size());
            HttpServletResponse hsr = ServletActionContext.getResponse();
            if(null == al){
                return ;
            }
            for(Article a : al){
                System.out.println(a.getId()+a.getDescription()+a.getTitle());
            }
            JSONArray json = new JSONArray();
            for(Article a : al){
                JSONObject jo = new JSONObject();
                jo.put("id", a.getId());
                jo.put("title", a.getTitle());
                jo.put("desc", a.getDescription());
                json.put(jo);
            }
            try {
                System.out.println(json.toString());
                hsr.setCharacterEncoding("UTF-8");
                hsr.getWriter().write(json.toString());
            } catch (IOException e) {
                e.printStackTrace ();
            }

(2) Use the static method of JSONArray under the net.sf.json package: fromObject(list).

--------------------------------------------------------------------------------------------------------------------

fastjson A package written by Alibaba Wen Shao to convert Object to json

package com.nubb.bean;

import java.io.Serializable;

public class Person implements Serializable{
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    private String address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
    
}
package com.nubb.test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.nubb.bean.Person;


public class JSONSerializer {
        private static final String DEFAULT_CHARSET_NAME = "UTF-8";

        public static <T> String serialize(T object) {
            return JSON.toJSONString(object);
        }

        public static <T> T deserialize(String string, Class<T> clz) {
            return JSON.parseObject(string, clz);
        }

        public static <T> T load(Path path, Class<T> clz) throws IOException {
            return deserialize(
                    new String(Files.readAllBytes(path), DEFAULT_CHARSET_NAME), clz);
        }

        public static <T> void save(Path path, T object) throws IOException {
            if (Files.notExists(path.getParent())) {
                Files.createDirectories(path.getParent());
            }
            Files.write(path,
                    serialize(object).getBytes(DEFAULT_CHARSET_NAME),
                    StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING);
        }
        
        public static void main(String[] args) {
            Person person1 = new Person();
            person1.setAddress("address");
            person1.setAge (11);
            person1.setName("amao");
            
            Person person2 = new Person();
            person2.setAddress("address");
            person2.setAge (11);
            person2.setName("amao");
            
            List<Person> lp = new ArrayList<Person>();
            lp.add(person1);
            lp.add(person2);
            System.out.println(serialize(lp));
        }
        
}
output:

[{"address":"address","age":11,"name":"amao"},{"address":"address","age":11,"name":"amao"}]


In addition, there are many open source frameworks for building json strings through object serialization

GSON:http://blog.csdn.net/axuanqq/article/details/51441590

Jsckson: http://itindex.net/detail/51074-java-%E5%88%A9%E7%94%A8-jackson

FastJson:http://blog.csdn.net/glarystar/article/details/6654494

Three performance comparisons: http://blog.csdn.net/accountwcx/article/details/50252657


     Pay attention to the WeChat public account and learn a little programmer's professional experience every day

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325639937&siteId=291194637