简体   繁体   中英

Gson Issue : Cannot map List<String> response to the Pojo class

I am having a microservice based architecture. One of my service calls another service api, and mostly we share the response class object, which makes it easy to map using gson.fromJson method.

Now, the issue which I have is that from one of the microservice api, the response I get in my parent service is of the type List<String> . And the parent service response pojo class is of following format:

public class ParentResposneClass {
        private List<String> list;
        //getter-setter etc
}

The parent api call piece of code is following (have removed unnecessary part):

CloseableHttpResponse response = closeableHttpClient.execute(postRequest);
String jsonResponse = EntityUtils.toString(response.getEntity(),StandardCharsets.UTF_8.name());
Logger.info(jsonResponse); // ["first","second"]
  • Problem 1

Now, if I would want to map the jsonResponse to my pojo response class ParentResposneClass :

gson.fromJson(jsonResponse, ParentResposneClass.class);

I get the error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2

And reason seems to be understandable. But my question is that is it possible to fix the above issue in this method.

  • Problem 2

If I don't go the gson way, and instead directly set the list object in ParentResposneClass :

ParentResposneClass parentResposneClass = new ParentResposneClass();
parentResposneClass.setList(convertStringToList(jsonResponse)); 
System.out.println(parentResposneClass.getList());

public static List<String> convertStringToList(String str) {
        str = str..replaceAll("\\[", "").replaceAll("\\]", ""));
        List<String> list = new ArrayList<String>(Arrays.asList(commaSepString.split("\\s*,\\s*")));
        return list;
}

This gives response ( parentResposneClass.getList() ) as "tag": ["\"first\"","\"second\""] with all these escape showing the json encoded string is still being retained.

So, is there a good way to solve this escape character issue without just directly replacing these from string.

PS: I know its a design issue where both microservice should have had shared the same response classes. But given this situation, is there a way we can solve either Problem 1 or Problem 2

For problem 1 I'd go:

var list = gson.fromJson(jsonResponse, new TypeToken<List<String>>(){}.getType())
var prc = new ParentResponseClass()
prc.setList(list);

I had tried something similar to this sometime back.

List result = gson.fromJson(jsonResponse, List.class);

ParentResposneClass parentResposneClass = new ParentResposneClass(); parentResposneClass.setList(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM