当前位置: 首页 > 知识库问答 >
问题:

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

酆光熙
2023-03-14

请记住,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伦敦”

共有1个答案

宋岳
2023-03-14

处理一个你一无所知的json结构是很少见的。如果你不知道你在寻找什么样的价值观,那么这些数据怎么会有用呢?

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

下面的代码显示了如何使用Jackson json库实现这一点

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

 类似资料:
  • 问题内容: 我目前正在开发一个Android项目,该项目需要我调用网络服务,该服务将返回一个json文件。我一直在使用GSON库来解析所有json文件并获取一个JSON对象。在我遇到关键字段是动态的json数据之前,它一直运行良好。此文件的示例如下: 我能够基于键ID“ 0”获得计数,但是我不确定如何利用该值来获取其他键对象(键ID 1-5),该键对象包含以下数据:我需要。如果有人在这件事上能帮助

  • 问题内容: 我有一个json对象是这样的: 我试图这样解析: 但是我不知道如何访问动态名称。我们如何解析这样的JSON -注意-Ya的 所有值都带有引号,例如:“ Yg&R_” 问题答案: 试试这个动态的JSON解析器

  • 问题内容: 有以下格式的JSON结果,JSON Lint将其显示为“有效响应”。 我的问题是:由于“ 141”,“ 8911”等都是动态值,我如何访问“ question_mark”的内容? 我的示例代码用于访问“产品”的价值。 我的问题标题“动态键”可能是错误的,但目前我不知道该问题的最佳名称是什么。 任何帮助将不胜感激! 问题答案: 使用JSONObject keys()获取密钥,然后迭代每个

  • 问题内容: 我想使用Api GSON通过java解析JSON文件以获取JSON文件的最后一个字段: 描述符.json: ListTeleServices.java: TeleService.java: Record.java: 最后是我的解析器类 JSONMainParse.java: 对我来说似乎正确,它应该显示:“ amine1”,但它在以下位置给了我一个 nullPointerExcepti

  • 我使用flink动态分析json类型的数据,对keyby和给定的列求和,在我的mapFunction中,我将json转换为case类,但结果流没有在keyby函数中得到编译器,在线程“main”org.apache.flink.api.common.InvalidProgramException中得到错误。我的代码如下所示 我如何将json转换为case类或tuple?

  • 问题内容: 我如何解析这个json对象: 我可以有N个端口,每个端口的值始终是key:value对。 到目前为止,我已经尝试过了: 有了这个我得到键(0,1),但值是空的。 我也尝试过这个: 但也不行。 这就是我解码json对象的方式: 问题答案: 使用此类型: 游乐场的例子 笔记: 字段名称非常匹配。我使用字段名称“ Ports”来匹配JSON文本中使用的名称。 Go类型在JSON中应具有相同级