JSON格式:com.alibaba fastjson1.2.39
JSON是一种键值对存储的格式,写在 {} 内:
其 key 必须用 双引号包括 如 "key",
其 key 和 value 之间用冒号 : 分隔,
其 value 有三种格式,分别为普通数字和字符串(需要写在 "" 内),数组(需要写在 [] 内),对象(需要写在 {} 内)
其 value 后使用逗号 , 分隔。
{
"key1":123,
"key2":"string",
"key3":{
"key4":123,
"key5":231
},
"key6":[1,2,3],
"key7":[{"key8":[1,2,3]},{"key9":[2,3]}]
}
JSON和JSONObject和jsonObject关系与区别:
JSON和JSONObject是alibaba的
jsonObject是Goole的
JSON是一个abstract抽象类,而JSONObject是JSON的一个实现类
所以JSON.xxx的方法和JSONObject.xxx的方法效果是一样的
JSONObject方法注意:
以下测试时 Book类中必须有无参构造方法,否则报错
create instance error, public com.example.demo.Book(java.lang.String,java.lang.Integer)
JSONObject.parseObject将 Json 字符串转换为指定的 Java 对象:
String str = "{"name":"语文","price":100}";
Book book = JSONObject.parseObject(str, Book.class);
System.out.println(book.getName());
语文
//必须有set方法,不然最后属性都为null
JSONObject.parseArray
将 Json 字符串转为指定的 Json数组:
String str = "[{"name":"语文","price":100},{"name":"数学","price":200}]";
List book = JSONObject.parseArray(str, Book.class);
System.out.println(book.get(1).getName());
数学
JSONObject.toJSONString
将对象转为 Json 字符串 (Map,List,对象皆可)
Book book1 = new Book("英语",300);
String s = JSONObject.toJSONString(book1);
System.out.println(s);
{"name":"英语","price":300}
JSONObject.toJSON
将 object 对象转为 JsonObject对象 (Map,List,对象皆可)
//JSONObject j = (JSONObject)book;转不了,预编译都过不去
JSONObject j = (JSONObject)JSONObject.toJSON(book);
System.out.println(j);
{"price":300,"name":"英语"}
JSONObject.get
根据 jsonObject 的 key 获取其对应的value (Object)
JSONObject jsonObject = JSONObject.parseObject(str);
Object key1 = jsonObject.get("key1");
123
JSONObject.getArray
根据 jsonObject 的 key 获取其对应的value (数组)
JSONArray key6 = jsonObject.getJSONArray("key6");
Object o = key6.get(0);
System.out.println(o);
1
JSONObject.getString
根据 jsonObject 的key 获取其对应的value (字符串)
String key2 = jsonObject.getString("key2");
System.out.println(key2);
string
JsonMapper.convertValue
将 json 字符串转为 Object 后进一步转为指定的 对象
String str = "{"name":"语文","price":100}";
Object parse = JSONObject.parse(str);
//Book o = (Book)parse; 不可以
//Book o = (Book)JSONObject.toJSON(parse); 不可以
JsonMapper jsonMapper = new JsonMapper();
Book b = jsonMapper.convertValue(parse,Book.class);
System.out.println(b);
Book{name='语文', price=100}


