Java “应为 BEGIN_OBJECT,但在第 1 行第 1 列处为 STRING”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28418662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:12:57  来源:igfitidea点击:

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

javajsonparsinggson

提问by Crapo Wolf

I have this method:

我有这个方法:

public static Object parseStringToObject(String json) {
    String Object = json;
    Gson gson = new Gson();
    Object objects = gson.fromJson(object, Object.class);
    parseConfigFromObjectToString(object);
    return objects;
}

And I want to parse a JSON with:

我想用以下方法解析 JSON:

public static void addObject(String IP, Object addObject) {
    try {
        String json = sendPostRequest("http://" + IP + ":3000/config/add_Object", ConfigJSONParser.parseConfigFromObjectToString(addObject));
        addObject = ConfigJSONParser.parseStringToObject(json);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

But I get an error message:

但我收到一条错误消息:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1

com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期为 BEGIN_OBJECT,但在第 1 行第 1 列处为 STRING

采纳答案by bhspencer

Even without seeing your JSON string you can tell from the error message that it is not the correct structure to be parsed into an instance of your class.

即使没有看到您的 JSON 字符串,您也可以从错误消息中看出它不是解析为类实例的正确结构。

Gson is expecting your JSON string to begin with an object opening brace. e.g.

Gson 期望您的 JSON 字符串以对象左括号开头。例如

{

But the string you have passed to it starts with an open quotes

但是您传递给它的字符串以开放引号开头

"

回答by BrantYu

Maybe your JSON Objectis right,but the response that you received is not your valid data.Just like when you connect the invalid WiFi,you may received a strange response < html>.....< /html>that GSONcan not parse.

也许你JSON Object是对的,但您收到的反应是不是你的,当你连接无效,例如有效data.Just WiFi,你可能会接到一个陌生的响应< html>.....< /html>GSON无法解析。

you may need to do some try..catch..for this strange response to avoid crash.

您可能需要try..catch..为这种奇怪的响应做一些事情以避免崩溃。

回答by Jessica Pennell

Invalid JSON from the server should always be an expected use case. A million things can go wrong during transmission. Gson is a bit tricky, because its error output will give you one problem, and the actual exception you catch will be of a different type.

来自服务器的无效 JSON 应该始终是预期的用例。传输过程中可能会出现一百万次错误。Gson 有点棘手,因为它的错误输出会给您带来一个问题,而您捕获的实际异常将是不同类型的。

With all that in mind, the proper fix on the client side is

考虑到所有这些,客户端的正确修复是

try
{
  gson.fromJSON(ad, Ad.class);
  //...
}
catch (IllegalStateException | JsonSyntaxException exception)
{
  //...

If you want to know why the JSON you received from the server is wrong, you can look inside your catch block at the exception. But even if it is your problem, it's not the client's responsibility to fix JSON it is receiving from the internet.

如果你想知道为什么你从服务器收到的 JSON 是错误的,你可以在你的 catch 块中查看异常。但即使是您的问题,修复它从 Internet 接收的 JSON 也不是客户的责任。

Either way, it is the client's responsibility to decide what to do when it gets bad JSON. Two possibilities are rejecting the JSON and doing nothing, and trying again.

无论哪种方式,客户端都有责任决定当 JSON 变得糟糕时该怎么做。两种可能性是拒绝 JSON 并且什么都不做,然后再试一次。

If you are going to try again, I highly recommend setting a flag inside the try / catch block and then responding to that flag outside the try / catch block. Nested try / catch is likely how Gson got us into this mess with our stack trace and exceptions not matching up.

如果您打算再试一次,我强烈建议在 try / catch 块内设置一个标志,然后在 try / catch 块外响应该标志。嵌套的 try / catch 很可能是 Gson 使我们陷入堆栈跟踪和异常不匹配的混乱局面的原因。

In other words, even though I'll admit it doesn't look very elegant, I would recommend

换句话说,即使我承认它看起来不太优雅,我还是会推荐

boolean failed = false;

try
{
  gson.fromJSON(ad, Ad.class);
  //...
}
catch (IllegalStateException | JsonSyntaxException exception)
{
  failed = true;
  //...
}

if (failed)
{
  //...

回答by Raj008

In Retrofit2, When you want to send your parameters in raw you must use Scalars.

在 Retrofit2 中,当您想以原始格式发送参数时,您必须使用标量。

first add this in your gradle:

首先在你的gradle中添加这个:

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.retrofit2:converter-scalars:2.3.0'

    public interface ApiInterface {

    String URL_BASE = "http://10.157.102.22/rest/";

    @Headers("Content-Type: application/json")
    @POST("login")
    Call<User> getUser(@Body String body);

}

my SampleActivity :

我的 SampleActivity :

   public class SampleActivity extends AppCompatActivity implements Callback<User> {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiInterface.URL_BASE)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiInterface apiInterface = retrofit.create(ApiInterface.class);


        // prepare call in Retrofit 2.0
        try {
            JSONObject paramObject = new JSONObject();
            paramObject.put("email", "[email protected]");
            paramObject.put("pass", "4384984938943");

            Call<User> userCall = apiInterface.getUser(paramObject.toString());
            userCall.enqueue(this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onResponse(Call<User> call, Response<User> response) {
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
    }
}

Reference: [How to POST raw whole JSON in the body of a Retrofit request?

参考:[如何在 Retrofit 请求的正文中发布原始的整个 JSON?

回答by Solomon Fissehaye

Don't use jsonObject.toStringon a JSON object.

不要jsonObject.toString在 JSON 对象上使用。

回答by Ravi Wadje

Make sure you have DESERIALIZED objects like DATE/DATETIME etc. If you are directly sending JSON without deserializing it then it can cause this problem.

确保你有 DESERIALIZED 对象,如 DATE/DATETIME 等。如果你直接发送 JSON 而没有反序列化它,那么它可能会导致这个问题。

回答by Wallace Roberto

I have come to share an solution. The error happened to me after forcing the notbook to hang up. possible solution clean preject.

我是来分享解决方案的。在强迫笔记本挂断后,错误发生在我身上。可能的解决方案clean preject

回答by RAJESH KUMAR ARUMUGAM

In my case, I am Returning JSON Object as

就我而言,我将 JSON 对象返回为

{"data":"","message":"Attendance Saved Successfully..!!!","status":"success"}

{"data":"","message":"出勤保存成功..!!!","status":"success"}

Resolved by changing it as

通过将其更改为解决

{"data":{},"message":"Attendance Saved Successfully..!!!","status":"success"}

{"data":{},"message":"出勤保存成功..!!!","status":"success"}

Here data is a sub JsonObject and it should starts from { not ""

这里的数据是一个子 JsonObject,它应该从 { 不是 ""

回答by Shabbir Ahmed

if your json format and variables are okay then check your database queries...even if data is saved in db correctly the actual problem might be in there...recheck your queries and try again.. Hope it helps

如果您的 json 格式和变量没问题,请检查您的数据库查询...即使数据正确保存在 db 中,实际问题也可能在那里...重新检查您的查询并重试...希望它有所帮助

回答by YazidEF

In my situation, I have a "model", consist of several String parameters, with the exception of one: it is byte array byte[]. Some code snippet:

在我的情况下,我有一个“模型”,由几个 String 参数组成,除了一个:它是 byte array byte[]。一些代码片段:

String response = args[0].toString();
Gson gson = new Gson();
BaseModel responseModel = gson.fromJson(response, BaseModel.class);

The last line above is when the

上面的最后一行是当

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column

is triggered. Searching through the SO, I realised I need to have some form of Adapterto convert my BaseModelto and fro a JsonObject. Having mixed of Stringand byte[]in a model does complicate thing. Apparently, Gsondon't really like the situation.

被触发。通过 SO 搜索,我意识到我需要某种形式Adapter来转换我BaseModel的 JsonObject。在模型中混合String和混合byte[]确实会使事情复杂化。显然,Gson不太喜欢这种情况。

I end up making an Adapterto ensure byte[]is converted to Base64format. Here is my Adapterclass:

我最终制作了一个Adapter以确保byte[]转换为Base64格式。这是我的Adapter课:

public class ByteArrayToBase64Adapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {

    @Override
    public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return Base64.decode(json.getAsString(), Base64.NO_WRAP);
    }

    @Override
    public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(Base64.encodeToString(src, Base64.NO_WRAP));
    }
}

To convert JSONObject to model, I used the following:

要将 JSONObject 转换为模型,我使用了以下内容:

Gson customGson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64Adapter()).create();
BaseModel responseModel = customGson.fromJson(response, BaseModel.class);

Similarly, to convert the model to JSONObject, I used the following:

同样,要将模型转换为 JSONObject,我使用了以下内容:

Gson customGson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64Adapter()).create();
String responseJSon = customGson.toJson(response);

What the code is doing is basically to push the intended class/object(in this case, byte[]class) through the Adapterwhenever it is encountered during the convertion to/fro JSONObject.

代码所做的基本上是将预期的class/object(在本例中为byte[]类)推Adapter送到 JSONObject 的转换过程中。