一种解决方案可能是这样写TypeAdapter
:
package stackoverflow.questions.q19332412;
import java.io.IOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.*;
public class BoxAdapter extends TypeAdapter<Box>
{
@Override
public void write(JsonWriter out, Box box) throws IOException {
out.beginObject();
out.name("w");
out.value(box.width);
out.name("d");
out.value(box.depth);
out.name("h");
out.value(box.height);
out.endObject();
}
@Override
public Box read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
in.beginObject();
Box box = new Box();
while (in.peek() == JsonToken.NAME){
String str = in.nextName();
fillField(in, box, str);
}
in.endObject();
return box;
}
private void fillField(JsonReader in, Box box, String str)
throws IOException {
switch(str){
case "w":
case "width":
box.width = in.nextInt();
break;
case "h":
case "height":
box.height = in.nextInt();
break;
case "d":
case "depth":
box.depth = in.nextInt();
break;
}
}
}
注意放入Box
和BoxAdapter
放入同一个包中。我将Box
字段的可见性更改为包可见以避免使用 getter/setter。但如果你愿意,你可以使用 getter/setter。
这是调用代码:
package stackoverflow.questions.q19332412;
import com.google.gson.*;
public class Q19332412 {
/**
* @param args
*/
public static void main(String[] args) {
String j1 = "{\"width\":4, \"height\":5, \"depth\"=1}";
String j2 = "{\"w\":4, \"h\":5, \"d\"=1}";
GsonBuilder gb = new GsonBuilder().registerTypeAdapter(Box.class, new BoxAdapter());
Gson g = gb.create();
System.out.println(g.fromJson(j1, Box.class));
System.out.println(g.fromJson(j2, Box.class));
}
}
这是结果:
框[宽度=4,高度=5,深度=1]
框[宽度=4,高度=5,深度=1]