我有一个像这样的对象:
public class Marketplace {
private String name;
private int id;
private List<String> supportedLanguages;
}
我有一个输入的Json格式的字符串,像这样:
{
"name":"US",
"id":1,
"supportedLanguages":{"en_US", "es_US"}
}
我首先尝试过类似的操作,但失败了:
objectMapper.readValue(marketplaceInJsonString, Marketplace.class);
然后我尝试了类似的操作,但仍然失败:
JsonNode jsonNode = objectMapper.readValue(marketplaceInJsonString, JsonNode.class);
Marketplace marketplace = new Marketplace(jsonNode.get("name").asText()), jsonNode.get("id").asInt(), jsonNode.findValuesAsText("supportedLanguages"));
我认为这里的关键问题是我找不到将supportedLanguages映射为字符串列表的正确方法。
Json String输入是否存在格式问题?
请帮助,并非常感谢。
答案 0 :(得分:1)
您的json字符串无效json
更改为
{
"name": "US",
"id": 1,
"supportedLanguages": [
"en_US",
"es_US"
]
}
测试代码:
String marketplaceInJsonString = "{\"name\":\"US\",\"id\":1,\"supportedLanguages\":[\"en_US\",\"es_US\"]}";
ObjectMapper objectMapper = new ObjectMapper();
Marketplace marketplace = objectMapper.readValue(marketplaceInJsonString, Marketplace.class);
System.out.println(marketplace);
//输出
Marketplace(name=US, id=1, supportedLanguages=[en_US, es_US])