如何使用ObjectMapper以Json格式读取包含String和List <string>的对象

时间:2019-04-07 15:22:48

标签: java json list objectmapper

我有一个像这样的对象:

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输入是否存在格式问题?

请帮助,并非常感谢。

1 个答案:

答案 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])