The difference between the three different JSONObject jar package

  • com.alibaba.fastjson.JSONObject
  • net.sf.json.JSONObject
  • org.json.JSONObject
way conversion between the java json objects and data in general, there are two, one is referenced third-party jar package, such as Gson (Google), Fastjson (Ali), Jackson, etc., in this way the advantage is concise syntax, you can achieve a if converted, but the disadvantage is the introduction of a large third-party libraries. 
The second is the direct use of Java comes org.json resolution, but this library feature comparison basis, the analysis will write a lot of duplicate code.

  

A, com.alibaba.fastjson.JSONObject use

1 POM.xml

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.51</version>
</dependency>

  

2 Json string conversion between Map, List, object

  of java.util.ArrayList Import; 
  Import the java.util.HashMap; 
  Import java.util.List; 
  Import a java.util.Map; 
  
  Import com.alibaba.fastjson.JSON; 
  Import com.alibaba.fastjson.JSONArray; 
  Import com.alibaba .fastjson.JSONObject; 
   
 public class TestFastJson { 
  
      public static void main (string [] args) { 
          json2JsonObject (); // Json string into the target JSONObject 
          json2JavaBean (); // converts a string to a JavaBean Json 
          json2JsonArray ( ); // Json string into the target JSONArray 
          json2JavaBeanList (); // converts a string to a JavaBean Json set 
          javaBean2Json (); // a JavaBean Json format into data 
          javaBean2JsonObject (); // convert a JavaBean the object is JSONObject
          json2ListInMap (); // Get Map Json string from the List object 
         the User the JSON = User.parseObject(s, User.class);
          list2JsonInMap (); // Map object into a list containing Json string 
          stringToMap (); // json string revolutions Map 
          mapToString (); // Map transfected json string 
          mapToJsonObject (); // map turn json objects 
          testList2String (); // list turn json string 
      } 
      
      Private static void json2JsonObject () { 
          string S = "{\" name \ ": \" Peter \ "}"; 
          the JSONObject Object = JSON.parseObject (S); 
          the System.out .println (object.get ( "name")); 
      } 
     
     Private static void json2JavaBean () { 
         String S = "{\" ID \ ": \" 17,051,801 \ ", \" name \ ": \" Lucy \ "} "; 
         System.out.println (user.getId ()); 
         System.out.println (the User.getName());
     }
     
     Private static void json2JsonArray () { 
         String S = "[{\" ID \ ": \" 17,051,801 \ ", \" name \ ": \" Lucy \ "}, {\" ID \ ": \" 17,051,802 \ " , "name \" \: \ "Peter \"}] "; 
         the JSONArray JSON.parseArray = Array (S); 
         {for (int I = 0 ++ I;; I <array.size ()) 
             data of // JSONArray converted to a String type requires outside plus ""; otherwise it will report the type of abnormal strong turn! 
             STR = array.get String (I) + ""; 
             the JSONObject Object = JSON.parseObject (STR); 
             System.out.println (object.get ( "name")); 
         } 
     } 
     
     Private static void json2JavaBeanList () {  
         String S = "
         List < User> list = JSON.parseArray (s, User.class);
         }
     }
     
      private static void javaBean2Json() {
         User user = new User("17051801", "lucy");
         String string = JSON.toJSONString(user);
         System.out.println(string);
     }
     
     private static void javaBean2JsonObject() {
         User user = new User("17051801", "lucy");
         JSONObject json = (JSONObject) JSON.toJSON(user);
         System.out.println(json.get("id"));
     }
     
     private static void json2ListInMap() {
         String s = "{json:[{id:\"17051801\",\"name\":\"lucy\"},{id:\"17051802\",\"name\":\"peter\"},"
                 + "{id:\"17051803\",\"name\":\"tom\"},{id:\"17051804\",\"name\":\"lily\"}]}";
         // convert Json string JSONObject object value of the object list and remove
         Object = JSON.parseObject the JSONObject (S); 
         Object objArray = object.get ( "JSON"); 
         String objArray + STR = ""; 
         // embodiment 1: in the form of an object is converted to JSONArray 
         JSONArray JSON.parseArray = Array (STR); 
         for (int I = 0; I <array.size (); I ++) { 
             the JSONObject obj = JSON.parseObject (array.get (I) + ""); 
             System.out.println (obj.get ( "name")) ; 
         } 
         // embodiment 2: is converted to List <JavaBean> form 
         List <the User> List = JSON.parseArray (STR, User.class); 
         for (the User User: List) { 
             System.out.println(user.getName());
         } 
     } 
     
     Private static void list2JsonInMap () { 
         // embodiment 1: Construction of an object with a list of JavaBean 
         School School School new new = (); 
         school.setId ( ". 1"); 
         school.setName ( "schoolA"); 
         
         the User new new user1 = the User (); 
         user1.setId ( "17,051,801"); 
         user1.setName ( " Lucy "); 
         the User new new user2 = the User (); 
         user2.setId (" 17,051,802 "); 
         user2.setName (" Peter "); 
         
         . school.getStudents () the Add (user1); 
         . school.getStudents () the Add (user2 ); 
         // convert the object into a JavaBean Json string 
         string string1 = JSON.toJSONString (School); 
         System.out.println (string1); 
         
         // embodiment 2: Construction of a Map objects with the list of
         Map<String, Object> map1 = new HashMap<String,Object>();
         map1.put("id", "17051801");
         map1.put("name", "lucy");
         
         Map<String, Object> map2 = new HashMap<String,Object>();
         map2.put("id", "17051802");
         map2.put("name", "peter");
         
         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
         list.add(map1);
         list.add(map2);
         
         Map<String, Object> map = new HashMap<String,Object>();
         map.put("id", "1");
         map.put("name", "schoolA");
         String string2 = JSON.toJSONString (map);
         // convert the object into a map Json string
         map.put ( "Students.", List);
         System.out.println(string2);
     }
 
      private static void stringToMap(){
          String str = "{\"age\":\"24\",\"name\":\"cool_summer_moon\"}";
          JSONObject  jsonObject = JSONObject.parseObject(str);
          //json对象转Map
          Map<String,Object> map = (Map<String,Object>)jsonObject;
          System.out.println("map对象是:" + map);
          Object object = map.get("age");
          System.out.println("age的值是"+object);
     }
     
     private static void mapToString(){
         Map<String,Object> map = new HashMap<>();
         map.put("age", 24);
         map.put("name", "cool_summer_moon");
         String jsonString = JSON.toJSONString(map);
         System.out.println("json string: "+ JSONString); 
     }
 
     private static void mapToJsonObject(){
        Map<String,Object> map = new HashMap<>();
        map.put("age", 24);
        map.put("name", "cool_summer_moon");
        JSONObject json = new JSONObject(map);
        System.out.println("Json对象是:" + json);
 
     }
 
     /** 
     * 测试包装类型的List转换为json字符串 
     */   
    public static void testList2String() {  
        List<Long> longs = new ArrayList<Long>();  
        longs.add(1L);  
        longs.add(2L);  
        longs.add(3L);  
        String actual = JSON.toJSONString(longs);  
        Assert.assertEquals("[1,2,3]", actual);  
    }
 
}

Two, org.json.JSONObject use

1. introduced org.json dependent

		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20160810</version>
		</dependency>

  

3.JSONObject turn javaBean

    public static void main(String[] args) {
        String str="{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}";
        Student stu = null;
        List<Student> list = null;
        try {
            ObjectMapper objectMapper=new ObjectMapper();
            StudentList studentList=objectMapper.readValue(str, StudentList.class);
            list=studentList.getStudent();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        for(Student s:list){
            System.out.println(s.getName());
        }
    }

 

  ObjectMapper objectMapper=new ObjectMapper();
  out = objectMapper.readValue(org.json.JSONObject.valueToString(arg0), OutputObject.class);

 

The use of three net.sf.json.JSONObject

Introducing a dependency maven

The need to retain the last line, there are two versions of the jdk realization: json-lib-2.1-jdk13.jar and json-lib-2.1-jdk15.jar

     <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

  

Examples of use

package json;

import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

public class JSONObject_1_3 {
public static void javaToJSON() {
System.out.println("java代码封装为json字符串");
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", "张三");
jsonObj.put("password", "123456");
System.out.println("java--->json \n" + jsonObj.toString());
}

public static void jsonToJAVA() {
System.out.println("json字符串转java代码");
String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
JSONObject jsonObj = JSONObject.fromString(jsonStr);
String username = jsonObj.getString("username");
String password = jsonObj.optString("password");
System.out.println("json--->java\n username=" + username
+ "\t password=" + password);
}

public static void jsonToXML() {
System.out.println("json字符串转xml字符串");
String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
JSONObject json = JSONObject.fromString(jsonStr);
XMLSerializer xmlSerializer = new XMLSerializer();
xmlSerializer.setRootName("user_info");
xmlSerializer.setTypeHintsEnabled(false);
String xml = xmlSerializer.write(json);
System.out.println("json--->xml \n" + xml);
System.out.println ( "turn JavaBean json string");
Public static void javaBeanToJSON () {
}

UserInfo userInfo = new UserInfo();
userInfo.setUsername("张三");
userInfo.setPassword("123456");
JSONObject json = JSONObject.fromBean(userInfo);
System.out.println("javabean--->json \n" + json.toString());
}

public static void javaBeanToXML() {
System.out.println("javabean转xml字符串");
UserInfo userInfo = new UserInfo();
userInfo.setUsername("张三");
userInfo.setPassword("123456");
JSONObject json = JSONObject.fromBean(userInfo);
XMLSerializer xmlSerializer = new XMLSerializer();
String xml = xmlSerializer.write(json, "UTF-8");
System.out.println("javabean--->xml \n" + xml);
}

public static void xmlToJSON(){
System.out.println("xml字符串转json字符串");
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user_info><password>123456</password><username>张三</username></user_info>";
JSON json=XMLSerializer.read(xml);
System.out.println("xml--->json \n"+json.toString());
}

public static void main(String args[]) {
  javaToJSON();
  jsonToJAVA();
  jsonToXML();
  javaBeanToJSON();
  javaBeanToXML();
  xmlToJSON();
}
}

 

Transfer: https://blog.csdn.net/zhengTornado/article/details/102832587

Guess you like

Origin www.cnblogs.com/gllegolas/p/12453031.html