Jsonobject and Jsonarray have different data representations:
Jsonobject data is represented by {}, for example: {"id": "1", "name": "ZhuZhu", "Age": "A", "Sex": "Male"}
Jsonarray is an array of jsonobject, which is {} enclosing a [] with one or more {}, such as [{"id": "1", "name": "ZhuZhu", "Age": "$", "sex": "Male " } ]
Summarize the jsonobject outer layer is {},jsonarray outer layer is [] Everybody processing data when must see clear data format, respectively use different method to process the data, otherwise it will be directly converted abnormal!
Below is a simple example of a jsonobject:
The packages introduced are:
Import Com.alibaba.fastjson.JSON;
Import Com.alibaba.fastjson.JSONArray;
Import Com.alibaba.fastjson.JSONObject;
@Test
publicvoid testjsonobject () { = "{id:\" 1\ ", name:\" zhuzhu\ ", age:\" 22\ ", sex:\" male \ "}"; = Jsonobject.parseobject (str); = Jsonobject.getinteger ("id"); = jsonobject.getstring ("name"); = Jsonobject.getstring ("Age"); = jsonobject.getstring ("Sex"); System.out.println ("I Am" +name+ "I Am" +age+ "year old, my sex is" +sex); }
The output is: I am zhuzhu I am 22 years old, my sex is male
A simple example of a jsonarray:
@Test
Public voidTestjsonarray () {String str= "[{\" id\ ": \" 1\ ", \" name\ ": \" zhuzhu\ ", \" age\ ": \" 22\ ", \" sex\ ": \" man \ "}]"; Jsonarray Jsonarray=Json.parsearray (str); Integer ID=NULL; String name=NULL ; String Age=NULL ; String Sex=NULL ; for(inti = 0; I < jsonarray.size (); i++) {Jsonobject jsonobject=(jsonobject) jsonarray.get (i); ID= Jsonobject.getinteger ("id"); Name= jsonobject.getstring ("name"); Age= Jsonobject.getstring ("Age"); Sex= jsonobject.getstring ("Sex"); } System.out.println ("I Am" +name+ "I Am" +age+ "year old, my sex is" +sex); }
The output is: I am zhuzhu I am 22 years old, my sex is male
Ok this is over, hope to help everyone, here also has a lot of not comprehensive place, just to give a simple reference, if there is a problem please criticize point out, thank you
The difference and usage of jsonobject and Jsonarray