Commonly used "small script"-json data processing


A little background:

The small scripts in our company's projects are some tool classes. For example, some methods of the MapUtil tool class are commonly used.

When writing the method of the company's MapUtil tool class, you should pay attention to the naming of the method name . Because of the method name, in a certain business process of the company's project, the String interception of the beginning string of the method name is then judged.


1. Recommended use of tools

1. Obtain the request url (the form of the interface-generally the data is json)

☺ Google Chrome is recommended, but other browsers are also acceptable.

Under network, refresh to get the target url


2. Get the target url (in json data format)

☺ We recommend Firefox browser. Search the target URL directly in the Firefox address bar to get the json data with beautified format.


3. Small details

(1) When using Google Chrome to obtain the target URL for copying, there is a small detail - select copy, do not select copy value

  • Because copy value will convert some parameters in the url to utf8 format



2. Json data of web pages and Map data of java code

The data structure in real business requirements is relatively complex, with multiple layers of nesting. For example, the json data of the request URL: a list is nested in the map, and then each element of the list is a map, and this map is nested in a map.

☺ Small details: Pay attention to whether the nested map is a map or a list ( because 0, 1, 2, 3, 4... may be index subscripts or just keys ):

  • Determine based on the folded shape of Firefox browser. For example, {} means map. If it is [], it means list.
  • If you are debugging an idea, you should also pay attention to the type hints in debug mode. Because in debug mode, for example, a set type data structure has 5 elements, it will store elements 0, 1, 2, 3, and 4 and then display them to you for observation, but if you notice that the type of the prompt is Set type If so, you will know that what is stored in the memory is definitely not stored continuously like 0, 1, 2, 3, and 4.

1. JSON data of web page

example:

☺ json data format features:

key:value

Key-value pairs are separated by colons


■ The essence of json data:

It's a string, a json string.


2. Map data of java code


☺Map data format features:

key=value

The key-value pairs are in the form of an equal sign


3-1. Business processing - mutual conversion between json and map [json serialization, deserialization]

(1) Recommended use: JsonUtil tool class

In fact, it encapsulates ObjectMapper's conversion of json and map. The toObject method encapsulates the readValue method, and toJson encapsulates the writeValueAsString method.

  • Convert json to map: JsonUtil. toObject (String content, Class valueType) The return value is a T type

    Or JsonUtil.toObject(String content, TypeReference valueTypeRef) returns a value of type T

    ▷ The return value is still of type T (equivalent to Object type). If you want to further convert the map, you can force it

  • Convert map to json: JsonUtil. toJson (Object obj)


■ Example-json to map:

/** 
* json字符串(非常普通的key:value)转成map
*/
String json = createJsonString("user","xiaoming");
       Object object1 = JsonUtil.toObject(json, new TypeReference<Object>() {
    
    });//或者使用方法JsonUtil.toObject(json, Object.class);效果也是一样的
        Map<String, Object> map1 = (Map<String, Object>) object1;
        System.out.println(map1.toString());
        System.out.println(map1.getClass());

	/*创建json字符串的方法*/
    public static String createJsonString(String key, Object value) {
    
    
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key, value);
        return jsonObject.toString();
    }


/** 
* json字符串(listmap)转成ListMap
*/
public static List<Map<String, Object>> toListMap(String json) {
    
    
    List<Object> list = JsonUtil.toObject(json,  new TypeReference<List<Object>>() {
    
    });
        List<Map<String, Object>> listw = new ArrayList<Map<String, Object>>();
        for (Object object : list) {
    
    
            Map<String, Object> ret = (Map<String, Object>) object;
            listw.add(ret);
        }
        return listw;
}   
/**
* map转成json字符串
*/
Map<String, Object> oldMap1 = new HashMap<>();
oldMap.put("1", "一");
String json = JsonUtil.toJson(oldMap);
System.out.println(json);

(2) Direct use: ObjectMapper

map in java can be divided into a larger range for processing - Object for processing

  • Convert json to map:

    readValue (String content, Class valueType) The return value is a T type

    Or readValue(String content, TypeReference valueTypeRef) returns a value of type T

    ▷ The return value is still of type T (equivalent to Object type). If you want to further convert the map, you can force it

  • Convert map to json:

    writeValueAsString(Object obj)

/**
* map转成json字符串
*/
Map<String, Object> oldMap1 = new HashMap<>();
oldMap.put("1", "一");
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(oldMap);
System.out.println(json);

3-2. In business, after converting the map into a json string, you want to obtain the key or value in the json string.

  • If the data is very simple and the amount is very small, you can use the relevant interception and merge functions of String, but it is not recommended because the key length of the json data is not fixed and interception is very troublesome.

Idea: Convert json string into json (node) object

Node: This understanding is the same as the node of the dom element. Each element can be understood as a node.


■ Example:

Details: If it is a JsonNode array, use jsonNode.elements(); to read each node in the array. If it is not a JsonNode array, use jsonNode.elements(); to return the values ​​of jsonNode.

//首先把嵌套map转换json字符串
String jsonStr = mapper.writeValueAsString(oldMap);
//把json字符串转换jsonNode节点对象,通过jsonNode可以获取到想要的字段
JsonNode jsonNode = mapper.readValue(jsonStr, JsonNode.class);

//迭代获取到jsonNode的values
Iterator<JsonNode> elements = jsonNode.elements();
while (elements.hasNext()) {
    
    
    JsonNode node = elements.next();
    System.out.println(node.toString());
}

//也可以迭代获取到jsonNode的keys
Iterator<String> keys = jsonNode.fieldNames();
while (keys.hasNext()) {
    
    
     String key = keys.next();
     System.out.println("key键是:" + key);
}

//通过key 获取到 value
JsonNode jNode = jsonNode.get(key);//得到value,value可能是普通的值,也可能是map


//获取到键值对
Iterator<Map.Entry<String,JsonNode>> jsonNodes = jsonNode.fields();  
   while (jsonNodes.hasNext()) {
    
      
       Map.Entry<String, JsonNode> node = jsonNodes.next();  
       System.err.println("遍历获取key:"+node.getKey());  
       System.err.println("遍历获取值:"+node.getValue().toString());
}

  • The JsonNode node object (see Object) is converted into a josn string using the JsonUtil.toJson(jsonNode) method.



3. Common sense about web pages

1. The web page cannot be opened

Reason: It may be that the website is on the external network and the network speed is limited; it may also be that the size of the webpage is too large (a common situation is that the webpage has many, many pictures), and the website is still on the external network;

Solution: VPN


2. When the webpage opens slowly, how to check the size and time of loading the webpage?

The difference between transferred over network and resources loaded by the page:

In fact, it is related to content-encoding: gzip; the difference between the two lies in compression. Transferred is the original size of all resources loaded by the front-end page after decompression .


■ You can also check the size of a certain request, such as the size of an image request.

Generally, by default, you can just check it directly (after all, after reading it, you are just making a rough prediction)


  • If you want to view the status of a request more accurately:


3. Make good use of the filtering items provided by the network

(1) Through filtering, retain interface requests


(2) Filter directly by keywords


4. About refreshing to obtain the request url

Key: What you are looking at is the layout of the page, such as scrolling layout. In order to get the URL, you need to scroll the page and refresh it;

General: Press F5 to refresh.

Analyze the specific situation in detail. For example, if you want to get the URL of a click event and open the network, click the button (button) and observe that a new URL is added to the network.


5. Quickly determine whether the page data is loaded synchronously or asynchronously

☺ Use Google Chrome and disable js . If you can still see page data after disabling js, it is synchronous data, otherwise it is asynchronous data.




If this article is helpful to you, please remember to give Yile a like, thank you!

Guess you like

Origin blog.csdn.net/weixin_45630258/article/details/129286513