1

I'm writing a framework for a web service api that return json. I use Jackson library to deserialize the json string. The api return a property to continue fetching the result of request. The response like this:

{
    continueToken:"token",
    results: [ 
                {
                },
             ]
}

All the responses have this structure. The only problem is that the name of the continue property differ from request to another. The name is like this

prefix + "continue"

I want to create only one class and to be able to map the json to this class. How can I do that? Here's what I want to have:

public class Response {
    private String continueToken;
    private List<Article> results;

    public Response (String continueToken, Article[] articles) {
         this.continueToken = continueToken;
         this.results = Arrays.asList(articles);
    }
}
//Here the name is ttcontinue
String json = request.get(type1);
Response r = jsonToResponse(json);

//Here the name is llcontinue
json = request.get(type2);
r = jsonToResponse(json);
Hunsu
  • 3,281
  • 7
  • 29
  • 64
  • Your question is confusing. So all responses have the `continueToken` variable but the requests have a different variable name in which to pass the `continueToken` ? Could you not take the token from the response and pass it into the right variable on the request and then serialize to json ? – Deepak Bala Jan 06 '15 at 19:17

1 Answers1

1

hm.. you have a dynamic field name, annotation solutions cannot work. Assuming there is no other JSON field ending in "continue" (which holds in your example), you can follow these steps:

  1. Iterate over the JSON keys as in this post
  2. Use field.getKey().endsWith("continue") to find your desired key
  3. Replace the key in your JSON node using code from this post with "continueToken"
  4. Now get your Response object
Community
  • 1
  • 1
Kostas Kryptos
  • 4,081
  • 2
  • 23
  • 24