0

I want to parse string JSON arrays to VO and using gson.

PostMan RequestBody Call my TestApi:

{"data": "[{\"id\":\"1\",\"name\":\"james\",\"passwd\":\"abcd\"},{\"id\":\"2\",\"name\":\"john\",\"passwd\":\"dcba\"},{\"id\":\"3\",\"name\":\"mike\",\"passwd\":\"opppt\"}]"}

My VO Class :

@Data
public class TestVo {
    private String id;
    private String name;
    private String passwd;
}

I tried this Code :

@PostMapping(value = "/testApi")
public void testApi(@RequestBody String data){

    Gson gson = new Gson();

    JsonElement jsonElement = gson.fromJson(data, JsonElement.class);

    String jsonStr = jsonElement.getAsJsonObject().get("data").getAsString();

    List<TestVo> list = gson.fromJson(jsonStr, new TypeToken<List<TestVo>>(){}.getType());
.
.
.

Output

Expected a string but was BEGIN_ARRAY at line 1 column ..... Error T.T

  • error code is { List list = gson.fromJson(jsonStr, new TypeToken>(){}.getType()); } here. get.("data") and getAsString dont cause error – HoyhandKlay Aug 08 '21 at 20:30
  • https://stackoverflow.com/a/5554296/12181863 if you take a look at this, the inner list in the .fromJson() method is using ArrayList. Can you try this and see if it helps? – YHStan Aug 08 '21 at 20:38
  • Your mappings do not match the expected input, hence wrong. Did you notice the `data` field? Additionally, why does your need to accept it as a string and do manual deserialization if Spring MVC can do that all for you just out of box? – terrorrussia-keeps-killing Aug 09 '21 at 06:34

0 Answers0