Java Gson-一个字段的两个json键

Java Gson-一个字段的两个json键,java,json,gson,Java,Json,Gson,我已经阅读了Gson文档并决定使用它。但我不知道如何为一个字段使用两个不同的JSON键。例如,我有: public class Box { @SerializedName("w") private int width; @SerializedName("h") private int height; @SerializedName("d") private int depth; } 对于width字段,如果在JSON字符串中找不到first,我希望使用keyw或

我已经阅读了Gson文档并决定使用它。但我不知道如何为一个字段使用两个不同的JSON键。例如,我有:

public class Box {

  @SerializedName("w")
  private int width;

  @SerializedName("h")
  private int height;

  @SerializedName("d")
  private int depth;

}
对于
width
字段,如果在JSON字符串中找不到first,我希望使用key
w
或可选key
width
对其进行反序列化

例如,
{“width”:3,“h”:4,“d”:2}
{“w”:3,“h”:4,“d”:2}
应作为Box类进行分析


如何使用注释或使用
typedapter

一种解决方案是编写一个
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;
        }
    }
}
这就是结果:

方框[宽度=4,高度=5,深度=1]

方框[宽度=4,高度=5,深度=1]


更新:

同样可以在
@SerializedName
注释中作为
alternate
名称实现

class Box {

    @SerializedName("w", alternate = ["width"])
    private val width: Int = 0

    @SerializedName("h", alternate = ["height"])
    private val height: Int = 0

    @SerializedName("d")
    private val depth: Int = 0
}

只是为了确定我理解你的问题。您想将{“宽度”:3,“h”:4,“d”:2}或{“w”:3,“h”:4,“d”:2}之类的东西反序列化到框中吗?
class Box {

    @SerializedName("w", alternate = ["width"])
    private val width: Int = 0

    @SerializedName("h", alternate = ["height"])
    private val height: Int = 0

    @SerializedName("d")
    private val depth: Int = 0
}