在JAVA中动态解析Json并找到键和值对?

问题描述 投票:0回答:1

请注意,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());
        }
    }
}



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

input:Address.street output: "23fn3 london"

java json parsing
1个回答
1
投票

处理一个你一无所知的json结构是不常见的。如果你不知道你要找的是什么值,那么这些数据怎么会有用呢?

在特殊情况下,你确实想翻阅整个树,你将不得不使用递归。因为每个字段(field)可以有一个简单的值("field": 1)、一个对象("field": {"b": 1})或一个数组("field": [1, 2, 3]).

下面的代码显示了如何使用 杰克逊图书馆

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: "[email protected]"
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

© www.soinside.com 2019 - 2024. All rights reserved.