【问题标题】:Read Json file using Jackson for the following Json structure and Obtain the Object使用 Jackson 读取 Json 文件,获取以下 Json 结构并获取对象
【发布时间】:2018-09-01 08:04:59
【问题描述】:

我可以读取一个简单的 json 文件,它有一个键值对,代码是

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class readconfig {
    public static void main(String Args[]) throws JsonParseException, JsonMappingException, IOException{
        // String inputjson = "{\"key1\":\"value1\", \"key2\":\"value2\", \"key3\":\"value3\"}"; 
        ObjectMapper mapper= new ObjectMapper();
        // readjson mp =mapper.readValue(inputjson, readjson.class);
        readjson mp =mapper.readValue(new FileInputStream("sam.json"), readjson.class );
        System.out.println(mp.getKey1());
    }
}

import java.io.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
public class readjson {
    public String k1;
    public String k2;
    public String k3;
    public key1 key;

    public key1 getKey() {
        return key;
    }
    public void setKey(key1 key) {
        this.key = key;
    }
    public String getKey1() {
        return k1;
    }
    public void setKey1(String key1) {
        this.k1 = key1;
    }
    public String getKey2() {
        return k2;
    }
    public void setKey2(String key2) {
        this.k2 = key2;
    }
    public String getKey3() {
        return k3;
    }
    public void setKey3(String key3) {
        this.k3 = key3;
    }
}

问题是我的 json 文件很复杂 这是我的 json 文件,它是地图的地图,内部地图的值是一个列表

{
 "key1":
  { "value1":
      ["listele1",
       "listele2"
      ]
  },
 "key2":
  { "value2":
     ["listele1",
     "listele2"
     ]
  },
 "key3":
 { "value3":
     ["listele1",
     "listele2"
     ]
  }
}

你能帮我修改列表中内部映射值的值,还可以反序列化 json 并将 json 作为对象获取

【问题讨论】:

    标签: java json object jackson json-deserialization


    【解决方案1】:

    首先,您应该更加遵守 Java 的命名约定……例如 ReadJson 而不是 readjsonString[] args 而不是 String Args[] - 它更方便且更易于阅读。

    现在解决您的问题……请注意,您的 ReadJson 必须反映与 JSON 数据相同的结构——因此它必须是一个带有字符串键的映射来映射值。后者再次带有字符串键和字符串值列表。

    这个集合可以使用下面的代码反序列化:

    Map<String, Map<String, List<String>>> readJson = MAPPER.readValue(inputjson, new TypeReference<Map<String, Map<String, List<String>>>>() {});
    

    所以要完整:

    public class LearningTest {
        public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
            String inputJson = "{ \"key1\": { \"value1\": [\"listele1\", \"listele2\" ] }, \"key2\": { \"value2\": [\"listele1\", \"listele2\" ] } }";
            Map<String, Map<String, List<String>>> readJson = new ObjectMapper().readValue(inputJson,
                    new TypeReference<Map<String, Map<String, List<String>>>>() {
                    });
            System.out.println(readJson.get("key1").get("value1").get(0));
        }
    }
    

    如您所见,此方法不再需要专用数据类 (ReadJson.java)。

    如果你想要一个列表中的所有列表元素,你可以这样实现:

    List<String> elements = readJson.values()             // Collection<Map<String, List<String>>>
        .stream()                                         // Stream<Map<String, List<String>>>
        .flatMap(value -> value.values().stream())        // Stream<List<String>>
        .flatMap(listOfStrings -> listOfStrings.stream()) // Stream<String>
        .collect(Collectors.toList());                    // List<String>
    
    System.out.println(elements);
    

    或者您可以访问单个列表,例如:

    List<String> listOfFirstInnerMap = readJson.get("key1").get("value1");
    List<String> listOfSecondInnerMap = readJson.get("key2").get("value2");
    

    【讨论】:

    • 谢谢它现在能够获取对象。现在我想获取列表元素。根据我的示例需要获取 listele1 这是内部映射的值你能帮我吗
    • 你想得到一个列表元素吗?嗯,如果我理解正确,您可以从内部地图中获取相应的信息。我已经相应地更新了我的答案。
    • 是的,再次感谢您的回答。它可以帮助我一次获取所有元素
    • 我已经将所有列表元素的获取添加到我上面的代码 sn-p 中。如果可行,请随意接受或投票。
    • 上面的代码为我提供了 json 结构中所有列表的所有元素,但我只需要一个列表的元素,你能帮我解决一下吗
    【解决方案2】:

    你的 json 映射到这个 Java 对象:

    Map<String, Map<String, String[]>>
    

    以下是一些您可以构建的代码:

    import com.fasterxml.jackson.databind.ObjectMapper;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class TestJson {
        public static void main(String[] args) throws Exception {
            Map<String, Map<String, String[]>> myFile = new HashMap<>();
    
            Map<String, String[]> subMap1 = new HashMap<>();
            Map<String, String[]> subMap2 = new HashMap<>();
            Map<String, String[]> subMap3 = new HashMap<>();
    
            String[] myArray = new String[] {"listele1", "listele2"};
    
            subMap1.put("value1", myArray);
            subMap2.put("value2", myArray);
            subMap3.put("value3", myArray);
    
            myFile.put("key1", subMap1);
            myFile.put("key2", subMap2);
            myFile.put("key3", subMap3);
    
            ObjectMapper mapper = new ObjectMapper();
    
            System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(myFile));
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-27
      • 1970-01-01
      • 2017-01-22
      • 2012-08-14
      • 2018-01-03
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      相关资源
      最近更新 更多