本文介绍了JsonSyntaxException Gson:预期为BEGIN_OBJECT,但为STRING的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试解密json数据,然后使用GSON将其转换为Scala case类.

I have been trying to decrypt json data and then convert it to Scala case class using GSON.

代码:

import com.google.gson.Gson

object DecryptQRData extends App {

  val key = "klix8TW3SMGtHLVO0ZbhwO8ggW0p+npHfB71epkvmE0="
  val data = "c3NbCs3KQ6uC9d1kplSOg78opMs5+jKB/n5O3D4ttLQaNfWeU/s3RxYqDMazA09gOhhUWkRHZo3xrsgv/x2zoQ=="
  val bytesArray: Array[Byte] = AES.decodeBase64(data)
  val finalData: Array[Byte] = AES.decrypt(bytesArray, key)

  val jsonString: String = new String(finalData)
  println(s"result: $jsonString")
  //result: "{\"username\": \"[email protected]\",\"address\": \"!Earth\"}"

  val gson: Gson = new Gson()
  val extractedJson: User = gson.fromJson(jsonString, classOf[User])
  println(s"user is: ${extractedJson}")
}

case class User(username: String, address: String)

以上代码失败,但出现以下异常:

Above code fails with below exception:

result: "{\"username\": \"[email protected]\",\"address\": \"!Earth\"}"
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
    at com.google.gson.Gson.fromJson(Gson.java:927)
    at com.google.gson.Gson.fromJson(Gson.java:892)
    at com.google.gson.Gson.fromJson(Gson.java:841)
    at com.google.gson.Gson.fromJson(Gson.java:813)
    at DecryptQRData$.delayedEndpoint$DecryptQRData$1(DecryptQRData.scala:15)
    at DecryptQRData$delayedInit$body.apply(DecryptQRData.scala:3)
    at scala.Function0.apply$mcV$sp(Function0.scala:39)
    at scala.Function0.apply$mcV$sp$(Function0.scala:39)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:17)
    at scala.App.$anonfun$main$1$adapted(App.scala:80)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.App.main(App.scala:80)
    at scala.App.main$(App.scala:78)
    at DecryptQRData$.main(DecryptQRData.scala:3)
    at DecryptQRData.main(DecryptQRData.scala)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $
    at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:215)
    ... 15 more

Process finished with exit code 1

但是当我更换

val jsonString: String = new String(finalData)
//jsonString contains "{\"username\": \"[email protected]\",\"address\": \"!Earth\"}"


val jsonString: String = "{\"username\": \"[email protected]\",\"address\": \"!Earth\"}",我的程序正常工作,并显示User.

with
val jsonString: String = "{\"username\": \"[email protected]\",\"address\": \"!Earth\"}", my program works and it prints User.

问题:当两个数据都包含相同数据时,为什么用实际数据替换jsonString有用.

Question: Why replacing jsonString with actual data works when both contains same data.

我尝试了以下代码(在开头和结尾都删除了引号)

Edit 1: I tried below code (removed quotes at beginning and end)

val jsonString: String = new String(finalData)
  println(s"jsonString: $jsonString")
  val removedQuotes = jsonString.replaceAll("^\"|\"$", "")
  println(s"removedQuotes: ${removedQuotes}")
  val gson: Gson = new Gson()
  val extractedJson: User = gson.fromJson(removedQuotes, classOf[User])
  println(s"user is: ${extractedJson}")

但是,它也失败,并显示以下错误:

But, it too fails with below error:

jsonString: "{\"username\": \"[email protected]\",\"address\": \"!Earth\"}"
removedQuotes: {\"username\": \"[email protected]\",\"address\": \"!Earth\"}
Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected name at line 1 column 2 path $.

推荐答案

这是因为您的JSON有效负载如下:

This is because your JSON payload looks like:

"{"username": "[email protected]","address": "!Earth"}

在开头请注意".当您首先删除"时,它将开始工作.请注意以下几行:

Notice " at the beginning. When you remove first " it will start working. Notice what below lines:

System.out.println("\"{}\"");
System.out.println("{}");

打印:

"{}"
{}

编辑

System.out.println("Start point: " + json);
json = json.substring(1, json.length() - 1);
System.out.println("Get without \": " + json);
json = json.replaceAll("\\\\\"", "\"");
System.out.println("Valid: " + json);

Gson gson = new Gson();
User user = gson.fromJson(json, User.class);

System.out.println(user);

上面的代码显示:

Start point: "{\"username\": \"[email protected]\",\"address\": \"!Earth\"}"
Get without ": {\"username\": \"[email protected]\",\"address\": \"!Earth\"}
Valid: {"username": "[email protected]","address": "!Earth"}
User{username='[email protected]', address='!Earth'}

另请参阅:

这篇关于JsonSyntaxException Gson:预期为BEGIN_OBJECT,但为STRING的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 11:37