I'm trying to de-serialize a string into a ("Length") object using Gson . But when I'm de-serializing the string 0.77 meter
it only de-serializes 0.77
.
Length class:
package test;
public class Length {
private final Unit unit;
private final double value;
public enum Unit {
METER;
}
public Length(double value, Unit unit) {
this.value = value;
this.unit = unit;
}
public double getValue() {
return value;
}
public Unit getUnit() {
return unit;
}
}
LengthDeSerializer class:
package test;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
public class LengthDeSerializer implements JsonDeserializer<Length> {
@Override
public Length deserialize(JsonElement source, Type type, JsonDeserializationContext jdc) throws JsonParseException {
System.out.println(source);
// De-serialization happens after this
// but the json element is already wrongly modified
return null;
}
}
Test class:
package test;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.measure.quantity.Length;
public class AppTest {
public AppTest() throws Exception {
String testString = "0.077 meter";
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(Length.class, new LengthDeSerializer());
Gson gson = gb.create();
gson.fromJson(testString, Length.class);
}
public static void main(String[] args) throws Exception {
new AppTest();
}
}
The output:
0.077
What am I doing wrong? Is this a known "problem"?
If it matters, I'm using Netbeans 8.1, Ubuntu 16.04, Gson 2.6.2, java 1.8.0_91
0.077 meter
Is NOT valid json. Try:
{"value":0.077, "unit":"meter"}
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.