您的位置:首页 > 移动开发 > Objective-C

使用 jackson ObjectMapper将java对象转换为json对象

2016-04-01 16:32 761 查看
自己做了一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,
"tencent@QQ.com" + 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": "tencent@QQ.com0",
"sex": "男",
"age": "23"
},
{
"userName": "test1",
"password": "pwd1",
"phone": "phone1",
"email": "tencent@QQ.com1",
"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,大家可以自行学习
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: