0

This may seem an odd requirement but I want to deserialize a JSONStringArray to a String, (not a String[]).

Example of my object

class Retailer {
  String name;
  String images;
}

Incoming JSON:

{
  "name":"Mr Retailer",
  "images":[
    "http://server.com/image1",
    "http://server.com/image2"
  ]
}

So the parsed object would contain the deserilized values like so:

name = "Mr Retailer"
images = "http://server.com/image1 http://server.com/image2"

The delimiter is not important I will pick one that does not exist in my URLs, e.g. pipe white space etc..

I'm assuming I need to write a TypeAdapter for String[] to iterate through the JSONArray and concat the elements in the array into a String?

I also only want to do this for that specific class, as other classes have String[] but I want to leave them alone.

Chris.Jenkins
  • 13,051
  • 4
  • 60
  • 61

2 Answers2

1

I think it would be easier to deserialize using the normal function(s), leaving you with

class Retailer {
  String name;
  String[] images;
}

and then either define a class that generates your desired class from that, or define a function String getImage() that returns the string from that array?

Nanne
  • 64,065
  • 16
  • 119
  • 163
  • I agree with you, but for a couple of reasons that not possible in this case. – Chris.Jenkins Feb 21 '14 at 12:35
  • 1
    Well, then you need to register a TypeAdapter indeed, but I would just do it for that `images` 'object'. See for instance this example: http://stackoverflow.com/questions/6014674/gson-custom-deseralizer-for-one-variable-in-an-object – Nanne Feb 21 '14 at 12:41
0

Based on @Nanne suggested link I created the following custom deserializer.

public class RetailerDeserializer implements JsonDeserializer<Retailer> {

    @Override
    public Retailer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject retailerObject = json.getAsJsonObject();
        final String name = retailerObject.get("name").getAsString();
        JsonArray innerImagesArray = retailerObject.get("innerImages").getAsJsonArray();
        String innerImages = null;
        if (innerImagesArray != null) {
            final String[] innerImagesArr = new String[innerImagesArray.size()];
            for (int i = 0; i < innerImagesArray.size(); i++) {
                innerImagesArr[i] = innerImagesArray.get(i).getAsString();
            }
            innerImages = TextUtils.join(" ", innerImagesArr);
        }
        return new Retailer(name, innerImages);
    }
}

I'm sure there are better my 'dynamic' suggestions. Any improvements on this I will be willing to accept as answers.

Chris.Jenkins
  • 13,051
  • 4
  • 60
  • 61