简体   繁体   English

GSON 无法使用字符串空间解析 JSON

[英]GSON fails parsing JSON with string space

I have the following object:我有以下对象:

public class ParameterWrapper<T> {

    private String type;

    private T value;

    public ParameterWrapper(String type, T value) {
        this.type = type;
        this.value = value;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }
}

I am serializing it into JSON using the Gson library.我正在使用 Gson 库将其序列化为 JSON。 When value contains a string with no spaces, it works perfectly.value包含一个没有空格的字符串时,它可以完美地工作。 When value contains a string with spaces, I see the following exception:value包含带空格的字符串时,我看到以下异常:

com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 28 com.google.gson.JsonSyntaxException:com.google.gson.stream.MalformedJsonException:第 1 行第 28 列未终止的对象

For the following JSON:对于以下 JSON:

{"Plaintext":{"type":"String","value":"hello there"},"Key":{"type":"Number","value":"1"},"SINGLE_FUNCTION":{"value":"1-0"}}

However with the following:但是,以下内容:

{"Plaintext":{"type":"String","value":"hellothere"},"Key":{"type":"Number","value":"1"},"SINGLE_FUNCTION":{"value":"1-0"}}

The JSON is parsed successfully. JSON 解析成功。 Is this a known issue?这是一个已知的问题? I've ran the JSON through a validator and it is perfectly fine.我已经通过验证器运行了 JSON,它非常好。

Edit:编辑:

The vagueness of the question wasn't unnoticed.问题的含糊性并没有被忽视。 I was hoping this was an existing issue.我希望这是一个存在的问题。 The application is huge, which is why prying out a small, compilable example is difficult, but I'll do what I can!应用程序是巨大的,这就是为什么很难撬出一个小的、可编译的示例,但我会尽我所能!

OKAY.好的。 So firstly, the below JSON is send to my controller:所以首先,下面的 JSON 被发送到我的控制器:

@RequestMapping("/update-state")
public
@ResponseBody
String updateState(@RequestParam(value = "algorithmId") String algorithmId,
                   @RequestParam(value = "state") String state) throws InvalidParameterException {

    Algorithm algorithm = algorithmService.getAlgorithmById(Integer.parseInt(algorithmId));
    algorithm.execute(executorService.parseAlgorithmState(state));

    return gsonBuilder.toJson(algorithm.getState().getParameterMap());
}

On the call to parseAlgorithmState(state) , it moves down to this method:在调用parseAlgorithmState(state) ,它向下移动到此方法:

@Override
public AlgorithmState parseAlgorithmState(String json) throws InvalidParameterException {
    Gson gson = new Gson();
    Map keyValueMap = (Map) gson.fromJson(json.trim(), Object.class);
    ...

The line Map keyValueMap = (Map) gson.fromJson(json.trim(), Object.class);Map keyValueMap = (Map) gson.fromJson(json.trim(), Object.class); is where the exception is initially occurring.是异常最初发生的地方。

So after some discussion, the following workaround worked:因此,经过一些讨论,以下解决方法有效:

Gson gson = new Gson(); 
JsonReader jr = new JsonReader(new StringReader(s.trim())); 
jr.setLenient(true); 
Map keyValueMap = (Map) gson.fromJson(jr, Object.class);

setLenient(true) makes the parser a bit less restrictive. setLenient(true)使解析器的限制更少。

Looking at the documentation every restrictions that setLenient(true) disable are not present in your Json string, except the first one (which may be the issue since you're getting the string from a webserver).查看文档,您的 Json 字符串中不存在setLenient(true)禁用的所有限制,除了第一个(这可能是问题,因为您是从网络服务器获取字符串)。

I just had this same issue.我刚刚遇到了同样的问题。 The problem is that the character is a non-breaking space, char(160).问题是字符是一个不间断的空格,char(160)。 If you paste this in the body of a request using POSTMAN, you'll visually be able to see the characters (They look like gray dots).如果您使用 POSTMAN 将其粘贴到请求正文中,您将能够在视觉上看到字符(它们看起来像灰点)。 Gson doesn't like them. Gson 不喜欢他们。

This worked for me这对我有用

  Gson gson = new Gson(); 
  Map keyValueMap = (Map) gson.fromJson(gson.toJson(s.trim()), Object.class);

I got the same error with this JSON:我在这个 JSON 中遇到了同样的错误:

{“id”:“”,“title”:“Hello SiteCore”,“description”:“This is the body text from SiteCore”,“type”:“Information”,“displayType”:“Banner”}

The parser was pointing to the char coming right after the first white space.解析器指向第一个空格之后的字符。

com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 26 path $.null

After much search and having some extra pairs of eyes, we found that the JSON (coming from a Sitecore database) has been created with instead of " .经过大量搜索和一些额外的眼睛,我们发现 JSON(来自 Sitecore 数据库)是用而不是"创建的。

Changing all chars to " solved my problem using the usual Gson code:使用通常的 Gson 代码将所有字符"更改为"解决了我的问题:

    @JvmStatic
    fun convertFromJsonString(data: String): Message? {
        if (data.isEmpty())
            return null
        return Gson().fromJson(data, Message::class.java)
    }

Hope this helps someone in the future.希望这对未来的人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM