【问题标题】:Using Gson with multiple values for object使用具有多个对象值的 Gson
【发布时间】:2012-02-19 18:30:46
【问题描述】:

我有这个 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();
      }
}

【问题讨论】:

  • 我认为你的结构有错误。据我了解,PrincipalTranslations 包含一个 Items 数组,每个 Items 有 2 个字段(termine 和 traduzione)。如果我是对的,请查看您的类声明,然后我可以为您发布一些有用的代码。

标签: java json serialization collections gson


【解决方案1】:

如果您想将对象称为零,则在您的“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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    相关资源
    最近更新 更多