使用带有多个值的Gson作为对象

时间:2012-02-19 18:30:46

标签: java json serialization collections gson

我有这个Json代码:

{
 "term" : {
   "PrincipalTranslations" : {
      "0" : {
            termine:"casa", 
            traduzione:"home"
            }
      "1" :{
             termine:"testa",
             traduzione:"head"
           }
       "2" :{
             termine:"dito",
             traduzione:"finger"
           }
   }
 }
}

如何反序列化对象0,1,2? 如果不是对象0,1,2我写了对象“零”(和停止),它的工作原理! 我已经使用过这个实现了:

public class Item {    
        private term term;

        public term getTERM() {
                return term;
        }  
}

public class term {
       private PrincipalTranslations PrincipalTranslations;

        public PrincipalTranslations getPrincipalTranslations() {
                return PrincipalTranslations;
        }      
}

public class PrincipalTranslations {
        private zero zero;

        public zero getZero() {
                return zero;
        }
}

public class zero {
        private String termine;

        public String gettermine() {
                return termine;
        }
}

并使用它,它打印(以正确的方式)“casa”

public class MainClass {

    public static void main(String[] args) throws IOException {

        FileReader reader = new FileReader("/home/peppe/test_ff"); 

        Gson gson = new GsonBuilder().create();

        Item p = gson.fromJson(reader, Item.class);
        System.out.print(p.getTERM().getPrincipalTranslations().getZero().gettermine());


        reader.close();
      }
}

1 个答案:

答案 0 :(得分:0)

如果要将对象调用为零,则在“Principal Translations”类中使用“SerializedName”注释:http://google-gson.googlecode.com/svn/tags/1.2.3/docs/javadocs/com/google/gson/annotations/SerializedName.html

看起来像这样:

@SerializedName("0")
public Zero zero;