反序列化

时间:2016-06-06 09:55:10

标签: java gson

我尝试使用 Gson 将字符串反序列化为("长度")对象。但是当我对字符串0.77 meter进行反序列化时,它只会反序列化0.77

长度等级:

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类:

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;

    }

}

测试类:

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();

    }

}

输出:

0.077

我做错了什么?这是一个已知的&#34;问题&#34;?

如果重要, 我使用的是Netbeans 8.1, Ubuntu 16.04,Gson 2.6.2, java 1.8.0_91

1 个答案:

答案 0 :(得分:1)

0.077 meter

无效的json。尝试:

{"value":0.077, "unit":"meter"}