【问题标题】:Json Parsing in Java Get the Values from array by Provding Keys only one Time?Java中的Json解析通过仅提供一次键从数组中获取值?
【发布时间】:2020-04-29 07:12:53
【问题描述】:

例如, 以下 JSON

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  }
]

当我们处理大量数组时,我们如何才能只获取一次键。比如 Give id 它一次又一次地给出所有数组的键。我只想获取 id 一次,当用户输入 id 时,它会给出整个数组中的 id 值。

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();
        Scanner scanner=new Scanner(System.in);
        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(entry.getKey() );
            }
            System.out.println();
            while (true) {
                System.out.println(map.get(scanner.next()));

            }

        } 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());
        }
    }
}

以下是代码结果和预期结果

key:0.address.city
Key:0.address.geo.lng
Key:0.name
Key:0.username

key:1.address.city
Key:1.address.geo.lng
Key:1.name
Key:1.username

output should like this with out index of array

name
username
address.city
address.geo.lng

 Graham
 Bret
 Gwenborough
 81.1496

 aham
 ret
 borough
 80.1496

------------------

【问题讨论】:

    标签: java json parsing jackson


    【解决方案1】:

    您可以创建一个Map&lt;String, List&lt;String&gt;&gt; 以便将一个键映射到它的所有值。例如。替换

    else if (node.isValueNode()) {
    ...
    }
    

    else if (node.isValueNode()) {
        ValueNode valueNode = (ValueNode) node;
        final List<String> values = map.getOrDefault(currentpath, new ArrayList<>());
        values.add(valueNode.asText());
        map.put(currentpath, values);
    }
    

    如果您现在输入 id,它将在列表中显示所有值。

    【讨论】:

    • 获取键很简单,我们只能返回第一个数组的索引来获取键,但问题是值,我们只需要提供一次键并获取所有值
    • 啊.. 我想现在我明白你在追求什么了。让我看看。
    • @saqibriaz 我编辑了我的答案。你能检查一下这是否适合你吗?
    • 是的,它接近我想要的。
    猜你喜欢
    • 2014-06-17
    • 1970-01-01
    • 2020-10-19
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多