gpt4 book ai didi

java - 将多个 Java Bean 转换为 JSON

转载 作者:行者123 更新时间:2023-11-29 23:20:37 28 4
gpt4 key购买 nike

我有多个相互关联的 Java bean 类(JSON 数组 + JSON 对象),因为它们具有嵌套结构。大约有10个类(class)。有没有办法集体转换这些类或至少一个一个地转换?我用我现在无法访问的 JSON 数据创建了这些类。所以,现在,我期待的是从这些类中创建一个虚拟 JSON。使用 GSON,我尝试转换其中一个 Bean 类,但是我得到的结果是空的。这是名为 Attachment.java 的 bean 之一。

Attachment.java

package mypackagename;

import java.io.Serializable;

public class Attachment implements Serializable{


private Payload payload;

private String type;

public Payload getPayload() {
return payload;
}

public void setPayload(Payload payload) {
this.payload = payload;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}
}

实现

Gson gson = new Gson();
Attachment attachment = new Attachment();
String json = gson.toJson(attachment);

enter image description here

最佳答案

确定你得到了一个空结果。因为你的 JSON 对象是空的。您应该向您的对象添加数据并再次测试它,如下所示:

Attachment attachment = new Attachment(new Payload("Test Payload"), "Test attachment");
String json = new Gson().toJson(attachment);
Log.e("Test", "Json: " + json); // result: Json: {"payload":{"test":"Test Payload"},"type":"Test attachment"}

为避免空对象,您必须为您的payloadtype 设置默认值,因为 Gson 将忽略任何空值。

关于java - 将多个 Java Bean 转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54376888/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com