JSON Jackson将多个密钥反序列化到同一字段中

时间:2019-07-16 20:23:29

标签: java json jackson deserialization

我正在尝试将JSON转换为POJO。 我曾与Jackson一起转换标准JSON文件。 在这种特殊情况下,我想将键值覆盖为“默认”类/变量。在这种情况下,有多个要替换的键值(即数百个,并且要替换的键值未知)。

这可能吗?我曾考虑过将其存储到Map中,然后将其迭代并存储到POJO中,但是想知道是否存在其他选择,因为我对将JSON存储到Map并不熟悉。

要处理的JSON示例:

"People" : {
    "person1" : { 
      "name" : "john doe",
      "address" : "123 main st",
      "email" : "john@doe.com"
    },
    "person2" : { 
      "name" : "bob cat",
      "address" : "234 dog st",
      "email" : "bob@cat.com"
    },
    "person3" : { 
      "name" : "foo bar",
      "address" : "111  1st ave",
      "email" : "foo@bar.com"
    },
    "person8" : { 
      "name" : "james bono",
      "address" : "999 alaska st",
      "email" : "james@bono.com"
    }
}

是否可以按以下结构生成类?主要问题是有数百种价值需要替换,并且假设它们是未知的,我不能使用这种方法。

@JsonIgnoreProperties(ignoreUnknown = true)
public class People { 

  @JsonAlias({"person1", "person2"})
  private List<Details> person; // --> this should be the default replacing person1, person2, and so on 

  private class Details { 
    String name;
    String address;
    String email;
  }
}

1 个答案:

答案 0 :(得分:1)

您可以对所有属性personXYZ使用JsonAnySetter注释。参见以下示例:

import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

        System.out.println(mapper.readValue(jsonFile, People.class).getPersons());
    }
}

class People {

    private List<Details> persons = new ArrayList<>();

    @JsonAnySetter
    public void setPerson(String name, Details person) {
        this.persons.add(person);
    }

    public List<Details> getPersons() {
        return persons;
    }

    public static class Details {
        String name;
        String address;
        String email;

        // getters, setters, toString
    }
}

对于上面的JSON代码,打印:

[Details{name='john doe', address='123 main st', email='john@doe.com'}, Details{name='bob cat', address='234 dog st', email='bob@cat.com'}, Details{name='foo bar', address='111  1st ave', email='foo@bar.com'}, Details{name='james bono', address='999 alaska st', email='james@bono.com'}]

如果您使用内部类,请记住将其设为public static以使其对Jackson实例化过程可见。

另请参阅: