【问题标题】:How to iterate a Map in JSON , when the values contains a List and the reference to the List is NULL当值包含 List 并且对 List 的引用为 NULL 时,如何在 JSON 中迭代 Map
【发布时间】:2019-03-12 03:25:41
【问题描述】:

该类返回JSON字符串,但包含List的Map值返回NULL指针异常。

尝试了提到的各种选项,仍然得到相同的空指针异常。

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    Map<String, Foo> foos = new HashMap<String, Foo>();
    foos.put("foo1", new Foo("foo1"));
    foos.put("foo2", new Foo(List<DetailMessage>));
    foos.put("foo3", null);
    foos.put(null, new Foo("foo4"));

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    // Since the DetailMessage field is null , Its throwing Null pointer //exception.
  }
}

【问题讨论】:

    标签: java spring rest jackson


    【解决方案1】:

    您遇到的问题是因为 null 值作为 Map 中的键,默认 JSON 结构是这样的

    {
       "Key1" : "Value1",
       "Key2" : "Value2"...
    } (This is the simplest form)
    

    在 JSON 中,我们不能有像 null : "value" 这样的东西,这违反了基本的 JSON 原则,因此 Object Mapper 无法将您的 Map 转换为 JSON String,您需要在 map 中包含所有非空键,为此上班

    所以删除行 foos.put(null, new Foo("foo4")); 将使您的代码工作

    即使 Map 允许 1 个 NULL 键,JSON 也不符合它,所以你会遇到这个错误

    希望对你有帮助!

    祝你好运!

    【讨论】:

    • 谢谢,我在 foos.put("foo2", new Foo(List));未设置空指针作为字段。
    • 我猜是同样的错误,您需要显示DetailMessage 中存在的代码以及您在地图中实际插入的方式foos.put("foo2", new Foo(List&lt;DetailMessage&gt;)) 在正常情况下应该是编译错误跨度>
    • com.fasterxml.jackson.databind.JasonMappingException:(was java.lang .NullPointerException) (通过引用链:java.util.HashMap["DetailMesage"]->java..util.ArrayList[ 0]->com.test.container.DetailMessage[fileMapper1])
    猜你喜欢
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    相关资源
    最近更新 更多