使用 jackson ObjectMapper將java對象轉換爲json對象

自己做了一java對象轉換爲json對象的小示例:JacksonTest.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;

public class JacksonTest {
    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        List<Person> persons = new ArrayList<Person>();
        Integer[] arrays = new Integer[2];
        Person person = null;
        for (int i = 0; i < 2; i++) {
            person = new Person("test" + i, "pwd" + i, "phone" + i,
                    "[email protected]" + i, "男", "23");
            persons.add(person);
            arrays[i] = i;
        }
        Map<String, String> tipMap = new HashMap<String, String>();
        tipMap.put("valueName", "10");
        tipMap.put("valueName2", "3");
        tipMap.put("valueName3", "5");
        tipMap.put("valueName4", "8");
        Map<String, Object> map2Json = new HashMap<String, Object>();
        // 加入list對象
        map2Json.put("personKey", persons);
        // 加入map對象
        map2Json.put("mapKey", tipMap);
        // 加入數組對象
        map2Json.put("idKey", arrays);      
        //轉化爲json字符串
        String json = objectMapper.writeValueAsString(map2Json);
        System.out.println(json);
    }
}

Person.java

import java.io.Serializable;

public class Person implements Serializable{
    private String userName;
    private String password;
    private String phone;
    private String email;
    private String sex;
    private String age;

    public Person(){}

    public Person(String userName, String password, String phone, String email,
            String sex, String age) {
        super();
        this.userName = userName;
        this.password = password;
        this.phone = phone;
        this.email = email;
        this.sex = sex;
        this.age = age;
    }
    。。。省略get()和set()方法
}

運行結果:

{
    "personKey": [{
        "userName": "test0",
        "password": "pwd0",
        "phone": "phone0",
        "email": "[email protected]",
        "sex": "男",
        "age": "23"
    },
    {
        "userName": "test1",
        "password": "pwd1",
        "phone": "phone1",
        "email": "[email protected]",
        "sex": "男",
        "age": "23"
    }],
    "mapKey": {
        "valueName": "10",
        "valueName2": "3",
        "valueName3": "5",
        "valueName4": "8"
    },
    "idKey": [0,1]
}

Jackson jar包的下載地址http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.jar

如果是首次使用該jar包還可以閱讀官方的示例:http://wiki.fasterxml.com/JacksonInFiveMinutes

github:https://github.com/FasterXML/jackson-core
當然該jar包還有許多其他的很多強大的api,大家可以自行學習

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章