1.json maven 依赖(以下都以第一个包为例)
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
(
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
)
2.JSON String 表示法,用转义字符表示:
String aa = "{\"1\":\"小红\",\"2\":\"小王\",\"3\":\"小明\",\"4\":\"小张\"}";
3.map转换为JSON
方法一:
Map<String, String> map = new HashMap<>();
map.put("1", "小红");
map.put("2", "小王");
map.put("3", "小明");
map.put("4", "小张");
map.put("5", "小赵");
ObjectMapper json = new ObjectMapper();
try {
String string = json.writeValueAsString(map);
JSONObject jsonObject = new JSONObject(string);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
方法2:
用maven引入fastjson jar包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.24</version>
</dependency>
Map<String, String> map = new HashMap<>(); map.put("1", "小红"); map.put("2", "小王"); map.put("3", "小明"); map.put("4", "小张"); map.put("5", "小赵"); String aString = JSON.toJSONString(map); System.out.println(aString);
4.JSON的解析
(1)第一个jar 包解析法:
String str = "{\"1\":\"小红\",\"2\":\"小王\",\"3\":\"小明\",\"4\":\"小张\"}";
JSONObject jsonObject = new JSONObject(str);
System.out.println(jsonObject.getString("1"));
System.out.println(jsonObject.getString("2"));
System.out.println(jsonObject.getString("3"));
多层JSON嵌套:
String jsonData="{\"name\":\"lily\",\"age\":23,\"addr\":{\"city\":guangzhou,\"province\":guangdong}}";
JSONObject jsonObject1 =new JSONObject(jsonData);
JSONObject jsonObject2 = jsonObject1.getJSONObject("addr");
System.out.println(jsonObject2.getString("city"));
(2)第二个jar包解析法(需要用[ ]把字符串包起来)
String aa = "[{\"1\":\"小红\",\"2\":\"小王\",\"3\":\"小明\",\"4\":\"小张\"}]";
JSONArray jsonArray = JSONArray.fromObject(aa);
if (jsonArray.size() > 0) {
// 遍历 jsonarray 数组,把每一个对象转成 json 对象
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.get("1"));
System.out.println(jsonObject.get("2"));
System.out.println(jsonObject.get("3"));
}
}
5.JSON 转换为替他格式
(1)to String
String str = jsonObject.toString();