json格式如下:
{
"msg":"success",
"total":0,
"code":0,
"data":[
{
"productId":32,
"picDetail":"detail1.png",
"pic":"p1.png"
},
{
"productId":31,
"picDetail":"detail2.png",
"pic":"p2.png"
}
]
}
代码示例:
安装依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
public class JsonStudy {
public static void main(String[] args) {
String ajson = "{\"msg\":\"success\",\"total\":0,\"code\":0,\"data\":[{\"productId\":32,\"picDetail\":\"detail1.png\",\"pic\":\"p1.png\"},{\"productId\":31,\"picDetail\":\"detail2.png\",\"pic\":\"p2.png\"}]}";
JSONObject jsonObject = (JSONObject) JSONObject.parse(ajson);
System.out.println(jsonObject.toString());
//获取 msg
System.out.println(jsonObject.get("msg"));
JSONArray jsonArray = jsonObject.getJSONArray("data");
System.out.println(jsonArray.get(0).toString());
String a = jsonArray.get(0).toString();
JSONObject jsonObject1 = (JSONObject) JSONObject.parse(a);
//获取productId
System.out.println(jsonObject1.get("productId"));
}
}