从JSON文件打印键值对

时间:2017-02-08 08:31:58

标签: java json jackson

我正在尝试从json文件中打印键值对。以下是我使用的代码。 我收到这个错误:

  

无法反序列化java.util.LinkedHashMap的实例   START_ARRAY令牌

我收到此错误,因为json格式是数组[{}]而不是对象{}。我无法改变传入的json文件。 我该怎么做?

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test4 {

    public static void main(String args[]) throws JsonProcessingException, IOException {
        ObjectMapper mapper = new ObjectMapper();


        /**
         * Read JSON from a file into a Map
         */
        try {
            Map<String, Object> map = mapper.readValue(new File(
                    "result.json"), new TypeReference<Map<String, Object>>() {
            });

           ;
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

0 个答案:

没有答案