如何使用ObjectMapper将Json格式读入包含String和List的Object

问题描述 投票:0回答:1

我有一个像这样的对象:

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映射为String列表的正确方法。

是否存在Json String输入的任何格式问题?

请帮忙,真的很感激。

java json list objectmapper
1个回答
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])
© www.soinside.com 2019 - 2024. All rights reserved.