我有以下对象:

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;
    }
}


我正在使用Gson库将其序列化为JSON。当value包含没有空格的字符串时,它可以完美工作。当value包含带空格的字符串时,我看到以下异常:


  com.google.gson.JsonSyntaxException:com.google.gson.stream.MalformedJsonException:第1行第28列的未终止对象


对于以下JSON:

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


但是具有以下内容:

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


JSON已成功解析。这是一个已知的问题?我已经通过验证器运行了JSON,这非常好。

编辑:

这个问题的模糊性并未引起人们的注意。我希望这是一个现有问题。该应用程序非常庞大,这就是为什么很难撬起一个小的可编译示例的原因,但是我会尽我所能!

好的。因此,首先,以下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());
}


在调用parseAlgorithmState(state)时,它会移至以下方法:

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


Map keyValueMap = (Map) gson.fromJson(json.trim(), Object.class);行是最初发生异常的位置。

最佳答案

我只是有同样的问题。问题在于该字符是一个不间断的字符char(160)。如果使用POSTMAN将其粘贴到请求的正文中,则可以直观地看到字符(它们看起来像灰色的点)。 Gson不喜欢他们。

10-07 19:32
查看更多