An example of conversion between Java Bean and JSON object
Conversion between Java Bean and JSON object
/** * 一 JSON.parSEObject() 单个对象 或map 大括号{} * 二 JSON.parseArray() 多个对象 数组[] 复杂的要在类中定义类 * 三 JSON.toJSONString() javaBean与JSON格式字符串之间的转换 * * 四 javaBean与json对象间的转换使用:JSON.toJSON(obj),然后使用强制类型转换,JSONObject或者JSONArray */ @Test public void testJson(){ // {"name":"小红","age":21,"nation":"中国"} 格式要进行格式化"\" String jsonPerson="{\"name\":\"小红\",\"age\":21,\"nation\":\"中国\"}"; System.out.println(jsonPerson);// {"name":"小红","nation":"中国"} String s = JSON.toJSONString(jsonPerson); // "{\"name\":\"小红\",\"nation\":\"中国\"}" System.out.println(s); //[{"text":"内存大小","value":"10M"},{"text":"颜色","value":"红色"}] // json转换为对象 Person person = JSON.parSEObject(jsonPerson,Person.class); System.out.println(person); System.out.println("============================================="); String jsonPerson2="[{\"name\":\"小红\",\"nation\":\"中国\"},{\"name\":\"小红2\",\"age\":31,\"nation\":\"中国2\"}]"; // Person person1 = JSON.parSEObject(jsonPerson2,Person.class); // System.out.println(person1); // com.alibaba.fastjson.JSONException: Syntax error,expect {,actual [,pos 0 List<Person> personList = JSON.parseArray(jsonPerson2,Person.class); System.out.println(personList); System.out.println("=============================================="); String result = "{\n" + " \"success\":\"true\",\n" + " \n" + " \"returnAddress\":\"123\"\n" + " \n}"; JSONObject jsonObject = JSON.parSEObject(result); System.out.println(jsonObject); // {"success":"true","returnAddress":"123"} Map map = JSON.parSEObject(result,Map.class); System.out.println(map); // {success=true,returnAddress=123} System.out.println("map取得的值时"+map.get("success")); // map取得的值时true System.out.println(jsonObject.toJSONString()); // {"success":"true","returnAddress":"123"} Map jsonObject1 = (Map) JSON.parSEObject(result); System.out.println(jsonObject1); // {"success":"true","returnAddress":"123"} System.out.println("jsonObject1取得的值时"+jsonObject1.get("success")); // jsonObject1取得的值时true } // 多重 javabean的方法是遍历
JSON. Parseobject (string STR) and jsonobject The difference between parseobject (string STR)
According to the source code, JSON is an abstract class. There is a static method parseobject (string text) in JSON, which parses text into a jsonobject object and returns it; Jsonobject is a class inherited from JSON. When calling jsonobject When parseobject (result), parseobject (string text) of the parent class will be called directly. Therefore, there is no difference between the two. One is to use the parent class to call the parent class's own static parseobject (string text), and the other is to use the child class to call the parent class's static parseobject (string text). The two call the same method.
The above is all the relevant knowledge points introduced this time. Thank you for your learning and support.