将JSON键值映射到Java中的类 [英] Map JSON key-value to class in java
本文介绍了将JSON键值映射到Java中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要通过键值将字符串JSON映射到 POJO 类中,但是我不确定是否存在一种更简单的方法来转换它.
I need to map string JSON by key-value into the POJO class, but I'm not sure there is an easier way to convert this.
我的课:
class Colors {
private String name;
private String color;
public String getName() { return name; }
public String getColor() { return color; }
}
JSON示例:
{
"white": "FFFFFF",
"red": "FF0000",
"black": "000000"
}
有什么办法(而不是使用foreach循环)在List<Colors>
中具有上述JSON?
Is there any way (instead of using foreach loop) to have the above JSON in List<Colors>
?
P.s:我尝试了与objectMapper.readValue
相同的问题,但没有成功.
P.s: I tried some same issue with objectMapper.readValue
, but didn't succeed.
推荐答案
您可以使用com.fasterxml.jackson.annotation.JsonAnySetter
批注,该批注将允许您处理每个key-value
对:
You can use com.fasterxml.jackson.annotation.JsonAnySetter
annotation which will allow you to handle each key-value
pair:
import com.fasterxml.jackson.annotation.JsonAnySetter;
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("./src/main/resources/test.json");
ObjectMapper mapper = new ObjectMapper();
Colors colors = mapper.readValue(jsonFile, Colors.class);
System.out.println(colors.getColors());
}
}
class Colors {
private final List<Color> colors = new ArrayList<>();
@JsonAnySetter
public void setAny(String key, String value) {
colors.add(new Color(key, value));
}
public List<Color> getColors() {
return colors;
}
}
class Color {
private String name;
private String color;
public Color(String name, String color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public String getColor() {
return color;
}
@Override
public String toString() {
return "Color{" +
"name='" + name + '\'' +
", color='" + color + '\'' +
'}';
}
}
上面的代码显示:
[Color{name='white', color='FFFFFF'}, Color{name='red', color='FF0000'}, Color{name='black', color='000000'}]
另请参阅:
这篇关于将JSON键值映射到Java中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文