1. 程式人生 > >JSON基礎(Java)

JSON基礎(Java)

ces exc end style ktr lock iba sonar 轉義字符

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();

JSON基礎(Java)