java - JAVA中的动态Json解析并找到键和值对?

标签 java json parsing

请记住,JSON 结构事先是未知的,即它是完全任意的,我们只知道它是 JSON 格式。

例如, 以下 JSON

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    {
    "Bar":"23",
    "Eek":"24"
  }
]
}
<小时/>

我们可以这样做来遍历树并跟踪我们想要找出点表示法属性名称的深度。

我们如何在编译时获取仅数据键和在运行时获取值。

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import java.io.File;
import java.io.IOException;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        File file=new File("src/data.json");
        ObjectMapper mapper=new ObjectMapper();
        try {

            LinkedHashMap<String,String> map= new LinkedHashMap<String, String>();
            JsonNode node =mapper.readTree(file);
            getKeys("",node, map);

            for (Map.Entry<String, String> entry : map.entrySet()) {
                System.out.println("Key:"+entry.getKey() + ""+"   "+" value:" + entry.getValue());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void getKeys(String currentpath,JsonNode node,LinkedHashMap map){
        if(node.isObject()){
            ObjectNode objectNode=(ObjectNode) node;
            Iterator<Map.Entry<String, JsonNode>> it=objectNode.fields();
            String prefix=currentpath.isEmpty()?"":currentpath+".";
            while (it.hasNext()){
                SortedMap.Entry<String,JsonNode> iter=it.next();
                getKeys(prefix+iter.getKey(),iter.getValue(),map);
            }
        }else if (node.isArray()){
            ArrayNode arrayNode=(ArrayNode) node;
            for(int i=0; i<arrayNode.size(); i++){
                getKeys(currentpath+i,arrayNode.get(i),map);
            }
        }
        else if(node.isValueNode()) {
            ValueNode valueNode=(ValueNode) node;
            map.put(currentpath,valueNode.asText());
        }
    }
}


<小时/>

在运行时仅显示用户想要的值。

喜欢

输入:地址.街道 输出:“23fn3 伦敦”

最佳答案

处理您一无所知的 json 结构并不常见。如果您不知道要寻找什么值,那么这些数据有何用处?

在特殊情况下,您确实想要遍历整个树,则必须使用递归。因为每个字段 (field) 都可以有一个简单的值 ("field": 1)、一个对象 ("field": {"b": 1} )或数组("field": [1, 2, 3])。

下面的代码展示了如何使用Jackson json library来做到这一点

public static void main(String[] args) throws IOException {
    File file = new File("data.json");
    ObjectMapper mapper = new ObjectMapper();

    JsonNode node = mapper.readTree(file);

    processNode(node);
}

private static void processNode(JsonNode node) {
    if(node.isArray()) {
        // if the node is a list of items,
        //  go through all the items and process them individually
        System.out.println("=== Array start ===");
        for (final JsonNode objInArray : node) {
            System.out.println("--- Array element start ---");
            // process the item in the array
            processNode(objInArray);
            System.out.println("--- Array element end ---");
        }
        System.out.println("=== Array end ===");
    } else if(node.isContainerNode()) {
        // if the node is an object,
        //  go through all fields within the object
        System.out.println("/// Object start ///");
        Iterator<Map.Entry<String, JsonNode>> it = node.fields();
        while (it.hasNext()) {
            Map.Entry<String, JsonNode> field = it.next();
            System.out.println("key: " + field.getKey());
            //process every field in the array
            processNode(field.getValue());
        }
        System.out.println("/// Object end ///");
    } else {
        // if node is a simple value (like string or int) so let's print it
        System.out.println("value: " + node);
    }
}

您提供的示例 json 给出以下输出:

=== Array start ===
--- Array element start ---
/// Object start ///
key: id
value: 1
key: name
value: "Leanne Graham"
key: username
value: "Bret"
key: email
value: "Sincere@april.biz"
key: address
/// Object start ///
key: street
value: " Light"
key: suite
value: "Apt. 556"
key: city
value: "Gwugh"
key: zipcode
value: "93874"
key: geo
/// Object start ///
key: lat
value: "-37.319"
key: lng
value: "81.146"
/// Object end ///
/// Object end ///
key: phone
value: "8031 x56442"
key: website
value: "hilded.org"
key: company
/// Object start ///
key: name
value: "Romra-Crona"
key: catchPhrase
value: " client-server neural-net"
key: bs
value: "harness markets"
/// Object end ///
/// Object end ///
--- Array element end ---
=== Array end ===

Process finished with exit code 0

关于java - JAVA中的动态Json解析并找到键和值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61204853/

相关文章:

java - 如何在jsoup解析之前暂停?

使用minidom的Python xml解析

java - 从子集合 Firestore/Android 中删除 map

java - Spring Tomcat 启动问题 setCatalinaBase(Ljava/io/File;)

java - 创建 json 对象

java - Gson- 将 JSON 对象的 JSON 数组解析为 ArrayList<org.json.JSONObject>

javascript - 使用自动 Id 增量将数据保存在数组中

html - 如何从 iOS 中的文件中解析 JSON?

java - ObjectInputStream.readobject() 在异常中抛出对象

json - Golang 将 2 个 JSON 项解码为 1 个结构