gpt4 book ai didi

java - 将 JSON 字符串转换为 Java 对象

转载 作者:行者123 更新时间:2023-12-02 03:44:21 26 4
gpt4 key购买 nike

我有一个由服务返回的字符串,采用以下 JSON 格式:

String message = {
"Tickets":
[{
"Type": "type1",
"Author": "author1",
"Rows":
[
{
"Price": "100.0",
"Date": "24/06/2016",
"Amount": "10"
},
{
"Type": "Comment",
"Value": "some comment goes here"
}
],
"ID": "165"
}],
"Desk": "desk1",
"User": "user1"
}

我需要解析它并转换为 Java 对象。我尝试创建一个这样的 dom:

public class TicketWrapper{
private Ticket ticket;
private String desk;
private String user;
}

public class Ticket {
private String type;
private String author;
private List<Row> rows;
private String id;
}

public class Row1{
private float price;
private Date date;
private int amount;
}

public class Row2{
private String type;
private float value;
}

然后我尝试用 Google Gson 解析它,这样:

TicketWrapper ticket = gson.fromJson(message, TicketWrapper.class)

但是如果我打印它System.out.println(gson.toJson(ticket)),它会打印:{“办公 table ”:0,“用户”:0}

我不知道如何将该Json解析为Java对象,以及如何告诉他“Rows”中的一行可以是Row1类型或Row2类型。

最佳答案

我认为存在一些问题,例如小写的属性名称、日期格式以及行的混合类型。我只是这样改变并为我工作:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import org.junit.Test;
import java.util.Date;
import java.util.List;

public class CheckTest {

@Test
public void thisTest() {
Gson gson = new GsonBuilder()
.setDateFormat("dd-MM-yyyy")
.setPrettyPrinting()
.create();
String message = "{\"Tickets\":" +
"[{\"Type\":\"type1\"," +
"\"Author\":\"author1\"," +
"\"Rows\":[{\"Price\":\"100.0\"," +
"\"Date\":\"24-06-2016\"," +
"\"Amount\":\"10\"}," +
"{\"Type\":\"Comment\"," +
"\"Value\":\"some comment goes here\"}]," +
"\"ID\":\"165\"}]," +
"\"Desk\":\"desk1\"," +
"\"User\":\"user1\"}";
TicketWrapper ticket = gson.fromJson(message, TicketWrapper.class);
System.out.println(ticket.toString());
}

public class TicketWrapper {
@SerializedName("Tickets")
private List<Ticket> tickets;
@SerializedName("Desk")
private String desk;
@SerializedName("User")
private String user;
public TicketWrapper() {
}
}

public class Ticket {
@SerializedName("Type")
private String type;
@SerializedName("Author")
private String author;
@SerializedName("Rows")
private List<Row> rows;
@SerializedName("ID")
private String id;

public Ticket() {
}
}

public class Row {
@SerializedName("Type")
private String type;
@SerializedName("Value")
private String value;
@SerializedName("Price")
private float price;
@SerializedName("Date")
private Date date;
@SerializedName("Amount")
private int amount;

public Row() {
}
}
}

关于java - 将 JSON 字符串转换为 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461991/

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