public class Users {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "{\"username\":\"" + username + "\", \"password\":\"" + password + "\"}";
}
}
package com.huawei.test;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
public class TestJson {
public static void main(String[] args) {
/**
* 将json字符串转换为 json对象
*/
//构建json字符串
String json = "{\"username\":\"lisi\",\"password\":\"123123\",\"address\":{\"province\":\"四川\"},\"fav\":[{\"name\":\"read\"},{\"name\":\"eat\"},{\"name\":\"run\"}]}";
//
//Object obj = JSONObject.stringToValue(json);
//通过构造器去构造json的实例
JSONObject jsonObject = new JSONObject(json);
//System.out.println(obj);
//得到对应键的值
System.out.println(jsonObject.get("username"));
System.out.println(jsonObject.getString("password"));
//得到json对象中的另一个对象
System.out.println(jsonObject.getJSONObject("address").get("province"));
//得到一个数组
JSONArray array = jsonObject.getJSONArray("fav");
//得到数组里面的值 有可能是基本值 有可能是对象
JSONObject o = array.getJSONObject(0);
System.out.println(o.get("name"));
Users users = new Users();
users.setUsername("zhangsan");
users.setPassword("123123123");
//必须重写toString方法 并返回构建的json字符串
Map<String, Object> map = new HashMap<String, Object>();
map.put("username", "testmap");
map.put("email", "test@test.com");
String str = JSONObject.valueToString(users);
System.out.println(str);
System.out.println(JSONObject.valueToString(map));
}
}