简体   繁体   English

Json 在 Java 中解析通过仅提供一次键从数组中获取值?

[英]Json Parsing in Java Get the Values from array by Provding Keys only one Time?

For example, The following JSON例如下面的 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"
    }
  }
]

How can we get the keys only once when we dealing with large number of arrays.like Give id it give the keys of all arrays again and again.当我们处理大量的 arrays 时,我们如何才能只获得一次密钥。就像一次又一次地给出所有 arrays 的密钥。 I just want to get id only once and when user enter id it gives values of id in whole array.我只想获取 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());
        }
    }
}

Below is code outcome and expected outcome以下是代码结果和预期结果

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

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

You could create a Map<String, List<String>> in order to map a key to all its values.您可以创建一个Map<String, List<String>>以便 map 成为其所有值的键。 Eg replace例如替换

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

with

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

If you now enter the id, it will show all values in a list.如果您现在输入 id,它将在列表中显示所有值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM