2013-10-12 46 views
1

我读过Gson文档并决定使用它。但我无法弄清楚我如何为一个字段使用两个不同的JSON密钥。例如,我有:Gson - 一个字段的两个json键

public class Box { 

    @SerializedName("w") 
    private int width; 

    @SerializedName("h") 
    private int height; 

    @SerializedName("d") 
    private int depth; 

} 

对于现场width,我想关键w或用作为选择键width反序列化,若先在JSON字符串没有找到。

例如,{"width":3, "h":4, "d":2}{"w":3, "h":4, "d":2}应该可以解析为Box类。

如何使用注释或可能使用TypedAdapter

+0

只是为了确保我能理解你的问题。你想反序列化一些类似于{“width”:3,“h”:4,“d”:2}或{“w”:3,“h”:4,“d”:2} – giampaolo

+0

trapo - 确实是) – jumper0k

回答

1

一种解决方案可能是写一个TypeAdapter像这样的:把BoxBoxAdapter到同一个软件包

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字段的可见性更改为可见包,以避免使用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,height = 5,depth = 1]