标签:转换方法 user alibaba ret this setname java ng2 json对象
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* Created by jiangzw on 2017/10/17.
*/
public class JsonDemo {
public static void main(String[] args) {
JsonDemo jsonDemo = new JsonDemo();
// jsonDemo.jsonString2JsonObject();
// jsonDemo.javaObject2JsonObject();
// jsonDemo.javaObject2JsonString();
// jsonDemo.jsonObject2JavaObject();
// jsonDemo.jsonString2JavaObject();
jsonDemo.map2JsonObject();
}
/**
* json字符串转换成json对象
*/
public void jsonString2JsonObject() {
String jsonString = "{\"name\":\"jzw\"}";
JSONObject jsonObject = JSON.parseObject(jsonString);
System.out.println(jsonObject.get("name"));
}
/**
* java对象转换成json对象
*/
public void javaObject2JsonObject() {
User user = new User("1001", "jzw");
JSONObject jsonObject = (JSONObject)JSON.toJSON(user);
System.out.println(jsonObject.get("id"));
}
/**
* java对象转换成json字符串
*/
public void javaObject2JsonString() {
User user = new User("1001", "jzw");
String jsonString = JSON.toJSONString(user);
System.out.println(jsonString);
}
/**
* json对象转换成java对象
*/
public void jsonObject2JavaObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", "1001");
jsonObject.put("name", "jzw");
User user = JSON.toJavaObject(jsonObject, User.class);
System.out.println("id= " + user.getId());
System.out.println("name= " + user.getName());
}
/**
* json字符串转换成java对象
*/
public void jsonString2JavaObject() {
String jsonString = "{\"id\":\"1001\", \"name\":\"jzw\"}";
User user = JSON.parseObject(jsonString, User.class);
System.out.println("id= " + user.getId());
System.out.println("name= " + user.getName());
}
/**
* map转换成json对象
*/
public void map2JsonObject() {
Map<String, String> map = new HashMap<String, String>();
map.put("id", "1001");
map.put("name", "jzw");
JSONObject jsonObject = (JSONObject)JSON.toJSON(map);
System.out.println(jsonObject.get("id"));
System.out.println(jsonObject.get("name"));
}
public static class User {
String id;
String name;
public User() {
}
public User(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
标签:转换方法 user alibaba ret this setname java ng2 json对象
原文地址:http://www.cnblogs.com/wutongin/p/7779094.html