GSON库

时间:2017-01-13 12:35:31

标签: java json gson

我有以下JSON

{ "name":"testapp2", "type":"Web", "packageName":"test2.com", "secretKey":{"0987654321","91287465827"}, "otpExpiry":"1800", "senderId":"VERIFY", "otpLength":"4", "requestPerIp":"500", "signature":"#OTP is your verification code" }

我正在编写我的自定义JSON读取器和编写器这是我的代码覆盖GSON TypeAdapter类这里是我的代码。我正在尝试捕获我的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;

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

2 个答案:

答案 0 :(得分:1)

请使用GSON Library,它提供从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

答案 1 :(得分:0)

  • 首先,您有无效的JSON:secretKey被声明为对象,而不是数组。
  • 其次,您忘了在case "secretKey"reader.endArray();中关闭数组。
  • 第三,secKey变量声明为null,因此它必须是空字符串"",以便不将"null"标记添加到secretKey 1}} field。

然而,自定义流读取非常适合大量数据集处理,但您似乎更好地使用简单的反序列化策略并将繁琐的反序列化作业直接委托给Gson:

让我们说,反序列化方法定义如下:

static Application deserializeApplication(final JsonReader reader) {
    return gson.<ApplicationIncomingDto>fromJson(reader, ApplicationIncomingDto.class).application();
}

这里的一个特例是ApplicationType,它在JSON中以字符串形式存储,但需要转换为ApplicationType。因此应该使用GsonBuilder,以便:

private static final Gson gson = new GsonBuilder()
        .registerTypeAdapter(ApplicationType.class, (JsonDeserializer<ApplicationType>) (json, typeOfT, context) -> new ApplicationType(json.getAsJsonPrimitive().getAsString()))
        .create();

您可以在其中绑定ApplicationType类和符合您需求的自定义JsonDeserializer实现。下面的代码片段声明了一个专门为数据反序列化设计的自定义数据传输对象,然后转换为您的Application类。但是,您可以直接反序列化为Application,但通常不是一个好主意(例如,您可以使用类似Gson的注释来注释DTO类字段;或者切换到另一个JSON库,并离开Application类就是这样。)

private static final class ApplicationIncomingDto {

    private final String name = null;
    private final ApplicationType type = null;
    private final String packageName = null;
    private final Integer otpExpiry = null;
    private final String senderId = null;
    private final Integer otpLength = null;
    private final Long requestPerIp = null;
    private final List<String> secretKey = null;
    private final String signature = null;

    private Application application() {
        final Application application = new Application();
        application.setName(name);
        application.setType(type);
        application.setPackageName(packageName);
        application.setOtpExpiry(otpExpiry);
        application.setSenderId(senderId);
        application.setOtpLength(otpLength);
        application.setRequestPerIp(requestPerIp);
        application.setSecretKey(secretKey.stream().collect(Collectors.joining()));
        application.setSignature(signature);
        return application;
    }

}

最后,它的使用方式:

out.println(deserializeApplication(new JsonReader(new StringReader(JSON))));

toString()Application都会覆盖输出(考虑ApplicationType):

  

应用{type = ApplicationType {name =&#39; Web&#39;},packageName =&#39; test2.com&#39;,otpExpiry = 1800,name =&#39; testapp2&#39;,senderId =&#39;验证&#39;,otpLength = 4,requestPerIp = 500,secretKey =&#39; 098765432191287465827&#39;,签名=&#39; #OTP是您的验证码&#39;,sendOTPInResponse = 0} < / p>