gpt4 book ai didi

java - GSON库中自定义读写方法

转载 作者:行者123 更新时间:2023-12-01 09:01:25 26 4
gpt4 key购买 nike

嗨,我有以下 JSON


{
“名称”:“testapp2”,
"type":"网络",
"packageName":"test2.com",
"secretKey":{"0987654321","91287465827"},
"otpExpiry":"1800",
"senderId":"验证",
"otp长度":"4",
"requestPerIp":"500",
"signature":"#OTP是您的验证码"
}

我正在编写我的自定义 JSON 读取器和编写器,这是我覆盖 GSON TypeAdapter 类的代码,这是我的代码。我正在 try catch 我的 JSON 对象并将其转换为我的自定义模型类...基本上我想解析嵌套 json 对象

public Application read(JsonReader reader) throws IOException {
Application application = new Application();
String secKey=null;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
switch (name) {
case "type":
ApplicationType type = new ApplicationType(reader.nextString());
application.setType(type);
break;
case "packageName":
application.setPackageName(reader.nextString());
break;
case "otpExpiry":
application.setOtpExpiry(reader.nextInt());
break;
case "name":
application.setName(reader.nextString());
break;
case "senderId":
application.setSenderId(reader.nextString());
break;
case "otpLength":
application.setOtpLength(reader.nextInt());
break;
case "requestPerIp":
application.setRequestPerIp(reader.nextLong());
break;
case "secretKey":
reader.beginArray();
while (reader.hasNext())
secKey+=reader.nextString();
application.setSecretKey(secKey);
break;
case "signature":
application.setSignature(reader.nextString());
break;
case "sendOTPInResponse":
application.setSendOTPInResponse(reader.nextInt());
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
return application;

此方法无法解析..请帮忙...

最佳答案

请使用 GSON 库,它提供从 JSONString 到模型的转换

您需要创建模型并传递 jsonString

在此创建 ModelCalss

public class Store  {
public String StoreId;
public String StoreDisplayLink;
public String StoreAddress;

}

GSON 库会将您的 JSONString 映射到您的模型

 private Store getStoreModel(String jsonStore) {

Type type = new TypeToken<Store>() {
}.getType();
Store store = new Gson().fromJson(jsonStore, type);
return store;

}

有关更多信息,请访问该链接

enter link description here

关于java - GSON库中自定义读写方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41634793/

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