我从服务器获得了这样的JSON:

{
  "id":"1",
  "value":13,
  "text":"{\"Pid\":\"2\",\"value\":42}"
}


我正在使用jackson库通过以下代码将此JSON字符串反序列化为java对象:(以下示例)

ObjectMapper mapper = new ObjectMapper();
MapObj obj = mapper.readValue(JSONfromServerInString, MapObj.class);


映射对象如下所示:

public class MapObj {
        @JsonProperty("id")
        private Integer id;
        @JsonProperty("value")
        private Integer value;
        @JsonProperty("text")
        private String text;

        public Integer getId() {return id;}
        public void setId(Integer id) {this.id = id;}
        public Integer getValue() {return value;}
        public void setValue(Integer value) {this.value = value;}
        public String getText() {return text;}
        public void setText(String text) {this.text = text;}
    }


但是,当我尝试在引号前使用反斜杠反序列化此String时。杰克逊解串器似乎在找到字符串的第一个结尾时就结束了。他无视那个反斜线。因此该示例将输出以下内容:


  org.codehaus.jackson.JsonParseException:意外字符(“ P”(代码80)):期望逗号分隔OBJECT条目
   在[来源:java.io.StringReader@2f7c7260;行:1,列:33]


((“ P”(代码80)代表原始JSON字符串\“ Pid \”中的P字符)

最佳答案

您确定它不起作用吗?此测试工作正常:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();

        String json = "{\n" +
                "  \"id\":\"1\",\n" +
                "  \"value\":13,\n" +
                "  \"text\":\"{\\\"Pid\\\":\\\"2\\\",\\\"value\\\":42}\"\n" +
                "}";

        MapObj mapObj = objectMapper.readValue(json, MapObj.class);
        System.out.println("text = " + mapObj.getText());
    }

    private static class MapObj {
        @JsonProperty("id")
        private Integer id;
        @JsonProperty("value")
        private Integer value;
        @JsonProperty("text")
        private String text;

        public Integer getId() {return id;}
        public void setId(Integer id) {this.id = id;}
        public Integer getValue() {return value;}
        public void setValue(Integer value) {this.value = value;}
        public String getText() {return text;}
        public void setText(String text) {this.text = text;}
    }
}


它打印:

text = {"Pid":"2","value":42}


使用杰克逊2.6.4

关于java - Jackson Parser无法读取String中的反斜杠引号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34858914/

10-09 14:01