简体   繁体   English

如何在Java中使用GSON将无名对象转换为JSON?

[英]How to convert nameless objects to JSON in java (using GSON)?

I was writing a program to return JSON object using gson and I discovered something peculiar. 我正在编写一个使用gson返回JSON对象的程序,发现了一些奇怪的东西。 Basically when I wanted to convert following object to JSON it gave me null. 基本上,当我想将以下对象转换为JSON时,它为我提供了null。

Customer customer = new Customer() {
    {
        setId(1);
        setName("Foo bar");
        setAddress("Some Address");
    }
};
System.out.println(gson.toJson(customer));

where Customer looks like this 客户看起来像这样

public class Customer{
    int id;
    String name;
    String address;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }   
}

but when I created object properly like 但是当我正确创建对象时

Customer customer = new Customer();
customer.setId(1);
customer.setName("Foo bar");
customer.setAddress("Some Address");
System.out.println(gson.toJson(customer));

it worked perfectly fine and gave output as supposed to. 它工作得很好,并按预期提供了输出。 Why does it matter how I create my objects. 为什么创建我的对象很重要。 Is there difference between two methods? 两种方法之间有区别吗?

The reason the first case it is returning null because 'customer' object's class is an anonymous one which clazz.isAnonymousClass() return true 第一种情况返回null的原因是因为“客户”对象的类是一个匿名类,而clazz.isAnonymousClass()返回true

See below for GSon implementation 参见下面的GSon实施

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM