java 对象映射器读取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42691591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ObjectMapper readValue
提问by lg0173
I load a ressource file json with the text format
我用文本格式加载资源文件json
{
"sources": [{
"prop1": "1",
"prop2": "2"
},
{
"prop1": "1",
"prop2": "2"
},
],
"redirection": [{
"prop1": "1",
"prop2": "2"
}
]
}
I have a class with this properties prop1 and prop2
我有一个具有这个属性 prop1 和 prop2 的类
I want to recover with ObjectMapper a list class. What the method ?
我想用 ObjectMapper 恢复一个列表类。什么方法?
This code doesn't work ....
此代码不起作用....
Map<String, Object> mp = mapper.readValue(jsonResource.getInputStream(),new TypeReference<Map<String, Object>>() {});
String sourceText= new ObjectMapper().readTree(jsonResource.getInputStream()).get("sources").asText();
mapper.readValue(sourceText, new TypeReference<List<MyClass>>(){});
Thanks for your help
谢谢你的帮助
回答by Yuriy Yunikov
In your case, I would write a custom JsonDeserializer
. Haven't really tested the code, but I think the idea is clear:
在你的情况下,我会写一个自定义JsonDeserializer
. 还没有真正测试过代码,但我认为这个想法很清楚:
final MyClassDeserializer myClassDeserializer = new MyClassDeserializer();
final SimpleModule deserializerModule = new SimpleModule();
deserializerModule.addDeserializer(MyClass.class, myClassDeserializer);
final ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(deserializerModule);
And the code for JsonDeserializer
:
和代码JsonDeserializer
:
public class MyClassDeserializer extends JsonDeserializer<MyClass> {
@Override
public MyClass deserialize(final JsonParser jsonParser, final DeserializationContext context)
throws IOException {
final JsonNode node = jsonParser.getCodec().readTree(jsonParser);
final JsonNode sourcesNode = node.get("sources");
if(node.isArray()) {
final ArrayNode arrayNode = (ArrayNode) node;
final Iterable<JsonNode> nodes = arrayNode::elements;
final Set<Source> set = StreamSupport.stream(nodes.spliterator(), false)
.map(mapper)
.collect(Collectors.toSet());
...
}
...
}
回答by SilverNak
First thing: Your JSON is invalid. There is a comma after the second object in the sources
array. This has to be deleted.
第一件事:您的 JSON 无效。sources
数组中的第二个对象后面有一个逗号。这个必须删除。
Second: I think you didn't choose the right type for your result. What your JSON represents is a map which maps from string to an array of objects. So the type should be something like Map<String, Props[]>
(Since you didn't provide the name of your class, I called it Props
.
第二:我认为你没有为你的结果选择正确的类型。您的 JSON 代表的是从字符串映射到对象数组的映射。所以类型应该是这样的Map<String, Props[]>
(因为你没有提供你的班级的名字,我把它叫做Props
.
With these considerations you can construct a MapType
by using ObjectMapper
s getTypeFactory()
method and deserialize the value using the constructed type like shown below.
考虑到这些因素,您可以MapType
使用ObjectMapper
sgetTypeFactory()
方法构造 a并使用构造类型反序列化值,如下所示。
ObjectMapper mapper = new ObjectMapper();
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Props[].class);
Map<String, Props[]> map = mapper.readValue(s, mapType);
回答by Essex Boy
I actually voted for the other answer, but this is my idea, to create the classes and let Hymanson do the work :
我实际上投票支持另一个答案,但这是我的想法,创建类并让 Hymanson 完成工作:
public class ResourceTest {
@Test
public void test1() throws IOException {
assertTrue(true);
Resource resource = new Resource();
resource.getRedirectrions().add(makeRedirectrion("rprop11", "rprop12"));
resource.getRedirectrions().add(makeRedirectrion("rprop21", "rprop22"));
resource.getSources().add(makeSource("sprop11","sprop12"));
resource.getSources().add(makeSource("sprop21","sprop22"));
String json = new ObjectMapper().writeValueAsString(resource);
System.out.println(json);
Resource resource1 = new ObjectMapper().readValue(json, Resource.class);
System.out.println(resource1);
}
private Source makeSource(String prop1, String prop2) {
Source source = new Source();
source.setProp1(prop1);
source.setProp2(prop2);
return source;
}
private Redirectrion makeRedirectrion(String prop1, String prop2) {
Redirectrion redirectrion = new Redirectrion();
redirectrion.setProp1(prop1);
redirectrion.setProp2(prop2);
return redirectrion;
}
}
Output is:
输出是:
{"sources":[{"prop1":"sprop11","prop2":"sprop12"},{"prop1":"sprop21","prop2":"sprop22"}],"redirectrions":[{"prop1":"rprop11","prop2":"rprop12"},{"prop1":"rprop21","prop2":"rprop22"}]}
Resource{sources=[Source{prop1='sprop11', prop2='sprop12'}, Source{prop1='sprop21', prop2='sprop22'}], redirectrions=[Source{prop1='rprop11', prop2='rprop12'}, Source{prop1='rprop21', prop2='rprop22'}]}