kingswanwho
kingswanwho

Reputation: 23

How to use ObjectMapper to read in an Json format to an Object which contains String and List<String>

I have an Object like this:

public class Marketplace {
    private String name;
    private int id;
    private List<String> supportedLanguages;
}

and I have an input Json format String like this:

{
"name":"US",
"id":1,
"supportedLanguages":{"en_US", "es_US"}
}

I tried something like this first but failed:

objectMapper.readValue(marketplaceInJsonString, Marketplace.class);

Then I tried something like this but still failed:

JsonNode jsonNode = objectMapper.readValue(marketplaceInJsonString, JsonNode.class);

Marketplace marketplace = new Marketplace(jsonNode.get("name").asText()), jsonNode.get("id").asInt(), jsonNode.findValuesAsText("supportedLanguages"));

I think the key problem here is that I don't find the correct way to map supportedLanguages as a List of String.

And is there any format problem of the Json String input?

Please help, and really appreciate.

Upvotes: 0

Views: 126

Answers (1)

dkb
dkb

Reputation: 4596

Your json string is not valid json
change it to

{
  "name": "US",
  "id": 1,
  "supportedLanguages": [
    "en_US",
    "es_US"
  ]
}

Testing code:

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); 

//output

Marketplace(name=US, id=1, supportedLanguages=[en_US, es_US])

Upvotes: 1

Related Questions