来自Json和toJson的Gson用于在Java中返回null的简单对象

问题描述 投票:2回答:2

问候我是新来的和Java,非常感谢您的建议。我正在使用gson-2.3.1,当我调用toJson或fromJson时,我意外地返回null。我是在一个更复杂的对象上尝试这个,所以我在这里用https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples用户指南回到基础。下面的代码几乎完全被复制,编译但是对我来说无法在返回的情况下返回null。只有字符串文字的情况才有效。建议非常感谢,谢谢!

    //an object
    class BagOfPrimitives {
        private int value1 = 1;
        private String value2 = "abc";
        private transient int value3 = 3;
        BagOfPrimitives() {
            // no-args constructor
        }
    }

    // (Serialization)
    BagOfPrimitives obj = new BagOfPrimitives();
    Gson expgson2 = new Gson();
    String json = expgson2.toJson(obj);
    // here json in null - expected was the string below
    String expectedjson = "{\"value1\":1,\"value2\":\"abc\"}";

    // (Deserialization)
    BagOfPrimitives obj2 = expgson2.fromJson(expectedjson, BagOfPrimitives.class);
    // result is obj2 is null and not the object expected
java object serialization gson
2个回答
3
投票

我发现了这个问题。上面的所有代码都在一个方法中,所以我在一个编译器允许的类中声明了类BagofPrimitives所以我认为它没问题。记住我是Java新手,还在学习。一旦我将BagofPrimitives移到它所属的位置,代码就可以了。


0
投票

虽然Ocean的上述答案是正确的,但我只想说问题出在文档上。看看guide,看起来BagOfPrimitives的内部阶级完全没问题,但实际上它甚至都不受支持。完整工作和非工作代码如下。请注意,两者都编译没有错误。

Works

package com.mypackage;
import com.google.gson.Gson;

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;

  BagOfPrimitives() {
  }
}

public class Trials {

  public static void main(String[] args) {
    BagOfPrimitives obj = new BagOfPrimitives();
    Gson gson = new Gson();
    String json = gson.toJson(obj);
    System.out.println(json);
  }
}

Output

{"value1":1,"value2":"abc"}

Doesn't work:

package com.mypackage;
import com.google.gson.Gson;

public class Trials {

  public static void main(String[] args) {

    class BagOfPrimitives {

      private int value1 = 1;
      private String value2 = "abc";
      private transient int value3 = 3;

      BagOfPrimitives() {
      }
    }

    BagOfPrimitives obj = new BagOfPrimitives();
    Gson gson = new Gson();
    String json = gson.toJson(obj);
    System.out.println(json);
  }
}

Output

null
© www.soinside.com 2019 - 2024. All rights reserved.