Java JSONObject 文本必须以“{”错误开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19399135/
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-12 16:49:16  来源:igfitidea点击:

A JSONObject text must begin with '{' error

javajson

提问by Pradeep Simha

I have this JSON coming from one of our REST service:

我有来自我们的 REST 服务之一的这个 JSON:

[
    "{\"category_name\":[\"Industry Components\"],\"categoryId\":[1]}",
    "{\"category_name\":[\"Business Components\"],\"categoryId\":[2]}",
    "{\"category_name\":[\"Utilities\"],\"categoryId\":[3]}",
    "{\"category_name\":[\"Tools\"],\"categoryId\":[4]}
]

I am using java-json.jar to parse this JSON, this is the simple snippet where I am trying to pass above JSON string:

我正在使用 java-json.jar 来解析这个 JSON,这是我试图在 JSON 字符串上方传递的简单片段:

JSONObject jsonObject = new JSONObject(jsonStr);

But I am getting below exception:

但我得到以下异常:

org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]

First I assumed it's because of [and ]characters in JSON and I tried to replace as below:

首先,我认为这是因为JSON 中的[]字符,我尝试替换如下:

String replacedStr = jsonStr.replaceAll("\[", "").replaceAll("\]", "")

But even then I am getting same exception. Can anyone please guide me to know what I am doing wrong?

但即便如此,我也遇到了同样的例外。谁能指导我知道我做错了什么?

采纳答案by popfalushi

I suppose that you should use not JSONObject, but JSONArray

我想你不应该使用 JSONObject,而是 JSONArray

回答by Sunil B N

JSON Object follows the following Structure:

JSON 对象遵循以下结构:

{
 "array": [
{
    color: "red",
    value: "#f00"
},
{
    color: "green",
    value: "#0f0"
}
]
}

JSON Array follows the following Structure:

JSON 数组遵循以下结构:

[
 { "firstName":"John" , "lastName":"Doe" }, 
 { "firstName":"Anna" , "lastName":"Smith" }, 
 { "firstName":"Peter" , "lastName": "Jones" }
]

回答by Amol Chaure

If you get JSONObject text must begin with '{' exception. Then first off all check what did u pass to the JSONObject constructor.

如果您得到 JSONObject 文本必须以 '{' 异常开头。然后首先检查你传递给 JSONObject 构造函数的内容。

You should pass the right json.txt file.So make sure what are u passing to jsonobject.

您应该传递正确的 json.txt 文件。所以请确保您传递给 jsonobject 的是什么。

String request = FileUtils.readFileToString(new File("/home/achaure/Downloads/Amol/KountRestTest/Documents/request.txt"));

JSONObject jsonObject = new JSONObject(request);

回答by Andres Navarro

instead

反而

JSONObject jsonObject = new JSONObject(jsonStr);

use

JSONArray jsonArray = new JSONArray(jsonStr);

and may be read about Gson is a nice library for parsing and work with json

并且可能会读到 Gson 是一个很好的用于解析和使用 json 的库