JSONObject的应用---读写Json

How to Set Json Request Body using ObjectMapper, JsonNode and ObjectNode一文中有介绍ObjectMapper的使用,它可以解析()json文件,也可以创建()json格式的结构,还可以用来修改json文件,这对API测试非常有用。本文中介绍另外一种处理json的类JSONObject,本人也是经常会混淆ObjectMapper,JSONObject和JSONPath,因为这几个类都处理JSON,在API Testing经常应用到。

Java提供很多JSON 包,来帮助我们处理JSON格式数据。经常用到的两个包是org.json and org.json.simple

什么是JSONObject

在Java中,JSONObject是name-value键值对的集合,是无序的,不可更改的。

JsonObject class represents an immutable JSON object value (an unordered collection of zero or more name/value pairs). It also provides unmodifiable map view to the JSON object name/value mappings.

例如在下述例子中,:first name, city, age是names, kelly,Shanghai,18分别是values

{
    
      
        "first name": "Kelly",  
        "city": "Shanghai",  
        "age": "18"  
}, 

Java JSONObject class

Java中的JSONObject类定义在org.json包,JSONObject值可以是Boolean, String, Number, JSONObject, JSONArray, JSONNumber, JSONString, 这些SONObject values 可以通过相应的方法获取,具体方法可以参考官网
Note: 在使用get()方法时,如果value找不到将会抛出异常,而opt()方法不会抛异常而是返回默认值,value可以为null。

从Json中获取Values

org.json例子

POM添加包依赖:

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20180813</version>
</dependency>
import org.json.*;  
public class GetValueFromJsonExample  
{
    
      
public static void main(String[] args) throws JSONException  
{
    
      
//constructor of the JSONObject class  
JSONObject obj = new JSONObject(  
"{" +  
"Employee ID: 092789," +  
"Employee Name: Helen Mirren," +  
"Age: 27, " +  
"Designation: Assistant Manager," +  
"City: Florida," +  
"Salary: 67000.00, " +  
"Experience: 26 " +  
"}"  
);  
//getting values form the JSONObject  
System.out.println("Employee ID: "+obj.getInt("Employee ID"));   
System.out.println("Employee Name: "+obj.getString("Employee Name"));  
System.out.println("Age: "+obj.getInt("Age"));   
System.out.println("Designation: "+obj.getString("Designation"));   
System.out.println("City: "+obj.getString("City"));  
System.out.println("Salary: "+obj.getDouble("Salary"));   
System.out.println("Experience: "+obj.getInt("Experience") +" Months");   
}  
} 

json-simple例子
JSONExample.json内容如下 :

{
    
    
     "lastName":"Smith",
    "address":{
    
    
        "streetAddress":"21 2nd Street",
         "city":"New York",
         "state":"NY",
         "postalCode":10021
    },
     "age":25,
     "phoneNumbers":[
            {
    
    
            "type":"home", "number":"212 555-1234"
            },
         {
    
    
            "type":"fax", "number":"212 555-1234"
         }
     ],
     "firstName":"John"
}
// Java program to read JSON from a file 
  
import java.io.FileReader; 
import java.util.Iterator; 
import java.util.Map; 
  
import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
import org.json.simple.parser.*; 
  
public class JSONReadExample  
{
    
     
    public static void main(String[] args) throws Exception  
    {
    
     
        // parsing file "JSONExample.json" 
        Object obj = new JSONParser().parse(new FileReader("JSONExample.json")); 
          
        // typecasting obj to JSONObject 
        JSONObject jo = (JSONObject) obj; 
          
        // getting firstName and lastName 
        String firstName = (String) jo.get("firstName"); 
        String lastName = (String) jo.get("lastName"); 
          
        System.out.println(firstName); 
        System.out.println(lastName); 
          
        // getting age 
        long age = (long) jo.get("age"); 
        System.out.println(age); 
          
        // getting address 
        Map address = ((Map)jo.get("address")); 
          
        // iterating address Map 
        Iterator<Map.Entry> itr1 = address.entrySet().iterator(); 
        while (itr1.hasNext()) {
    
     
            Map.Entry pair = itr1.next(); 
            System.out.println(pair.getKey() + " : " + pair.getValue()); 
        } 
          
        // getting phoneNumbers 
        JSONArray ja = (JSONArray) jo.get("phoneNumbers"); 
          
        // iterating phoneNumbers 
        Iterator itr2 = ja.iterator(); 
          
        while (itr2.hasNext())  
        {
    
     
            itr1 = ((Map) itr2.next()).entrySet().iterator(); 
            while (itr1.hasNext()) {
    
     
                Map.Entry pair = itr1.next(); 
                System.out.println(pair.getKey() + " : " + pair.getValue()); 
            } 
        } 
    } 
} 

创建Json

org.json 例子
例如创建一个ES json 查询:查询sentiment为NEUTRAL且expert_id为5fdb9d048ccd9819e3b3d70b记录。

{
    
    
	"query": {
    
    
		"bool": {
    
    
			"must": [
				{
    
    
					"match": {
    
    
						"sentiment": "NEUTRAL"
					}
				},
				{
    
    
					"match": {
    
    
						"expert_id": "5fdb9d048ccd9819e3b3d70b"
					}
				}
			]
		}
	}
}
import org.json.*;  
public class Test {
    
    
public static void main(String[] args)   
{
    
    
        JSONObject sentimentJsonNodes = new JSONObject();

        JSONObject sentimentNode = new JSONObject();
        sentimentNode.put("sentiment", sentiment);

        JSONObject matchNodeOne = new JSONObject();
        matchNodeOne.put("match", sentimentNode);

        JSONObject expertIDNode = new JSONObject();
        expertIDNode.put("expert_id", expertID);

        JSONObject matchNodeTwo = new JSONObject();
        matchNodeTwo.put("match", expertIDNode);

        JSONArray matchList = new JSONArray();

        matchList.put(matchNodeOne);
        matchList.put(matchNodeTwo);

        JSONObject mustNode = new JSONObject();
        mustNode.put("must", matchList);

        JSONObject boolNode = new JSONObject();
        boolNode.put("bool", mustNode);

        sentimentJsonNodes.put("query", boolNode);

       System.out.print(sentimentJsonNodes.toString());
    }
}

json.simple 例子
build下面这个json

扫描二维码关注公众号,回复: 12718831 查看本文章
{
    
    
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
    
    
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    },
    "phoneNumbers": [
        {
    
    
            "type": "home",
            "number": "212 555-1234"
        },
        {
    
    
            "type": "fax",
            "number": "646 555-4567" 
        }
    ] 
}
// Java program for write JSON to a file 
  
import java.io.FileNotFoundException; 
import java.io.PrintWriter; 
import java.util.LinkedHashMap; 
import java.util.Map; 
import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
  
public class JSONWriteExample 
{
    
     
    public static void main(String[] args) throws FileNotFoundException  
    {
    
     
        // creating JSONObject 
        JSONObject jo = new JSONObject(); 
          
        // putting data to JSONObject 
        jo.put("firstName", "John"); 
        jo.put("lastName", "Smith"); 
        jo.put("age", 25); 
          
        // for address data, first create LinkedHashMap 
        Map m = new LinkedHashMap(4); 
        m.put("streetAddress", "21 2nd Street"); 
        m.put("city", "New York"); 
        m.put("state", "NY"); 
        m.put("postalCode", 10021); 
          
        // putting address to JSONObject 
        jo.put("address", m); 
          
        // for phone numbers, first create JSONArray  
        JSONArray ja = new JSONArray(); 
          
        m = new LinkedHashMap(2); 
        m.put("type", "home"); 
        m.put("number", "212 555-1234"); 
          
        // adding map to list 
        ja.add(m); 
          
        m = new LinkedHashMap(2); 
        m.put("type", "fax"); 
        m.put("number", "212 555-1234"); 
          
        // adding map to list 
        ja.add(m); 
          
        // putting phoneNumbers to JSONObject 
        jo.put("phoneNumbers", ja); 
          
        // writing JSON to file:"JSONExample.json" in cwd 
        PrintWriter pw = new PrintWriter("JSONExample.json"); 
        pw.write(jo.toJSONString()); 
          
        pw.flush(); 
        pw.close(); 
    } 
} 

总结:

JSONObject可以读Json获取信息,也可以写入一个Json文件,但是不能Edit一个已经存在的Json,因为JSONObject是immutable不可能更改的。

参考:
How to parse JSON in Java
Interface JsonObject
How to Get Value from JSON Object in Java Example

猜你喜欢

转载自blog.csdn.net/wumingxiaoyao/article/details/114228191
今日推荐