0

Currently I'm trying to parse a json object in Java using gson. But I am not familiar with Java that much but I had done this same project on C# some months ago. I need to serialize a field using a custom JosnConverter. The code I used in my c# project.

public class ValueConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value.ToString());
        writer.Flush();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }
} 

And I define the field like

[JsonProperty("id"), JsonConverter(typeof(ValueStringConverter))]
public long Id { get; set; }

How do I achieve the same thing using Gson? I have tried to look at TypeAdapter but I am not sure that is what I need or not.

Writwick
  • 2,133
  • 6
  • 23
  • 54
  • Gson doesn't have targeted converters, ie. you can't specify a converter for a single field. Consider using Jackson and its `@JsonSerialize` annotation. – Sotirios Delimanolis Mar 27 '15 at 19:04
  • Dawn. I have to rewrite the whole code again then :( – Writwick Mar 28 '15 at 02:31
  • Finally using this example here: http://stackoverflow.com/questions/11271375/gson-custom-seralizer-for-one-variable-of-many-in-an-object-using-typeadapter and manually editing the required fields in `beforeWrite`. – Writwick Mar 28 '15 at 18:08

0 Answers0