java - 如何使用 ObjectMapper 将 JSON 值视为 Java 中的字符串对象?

标签 java json jackson

我在将 Json 转换为 Java 对象时遇到问题。 我的“jsonText”字段有 json 作为值,我想将其放置在字符串中。我的自定义类具有以下结构。

Class Custom{
    @JsonProperty(value = "field1")
    private String field1;
    @JsonProperty(value = "jsonText")
    private String jsonText;
}

下面是我的代码:

ObjectMapper mapper = new ObjectMapper();

JsonNode node = mapper.readTree(inputString);
String nodeTree = node.path("jsonText").toString();
List<PatientMeasure> measuresList =mapper.readValue(nodeTree,
                            TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, CustomClass.class) );

要转换的 Json 是:

    "field1" : "000000000E",                
    "jsonText" : {
        "rank" : "17",
        "status" : "",
        "id" : 0
    }

出现异常:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.StringReader@3362f02f; line: 1, column: 108] (through reference chain: com.Custom["jsonText"])

最佳答案

你可以试试这个:

JSONArray ar= new JSONArray(result);
JSONObject jsonObj= ar.getJSONObject(0);
String strname = jsonObj.getString("NeededString");

关于java - 如何使用 ObjectMapper 将 JSON 值视为 Java 中的字符串对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41380877/

相关文章:

如果字符串包含非法字符,则返回 Java 函数

java - Android 登录应用程序 - 显示电子邮件

java - 使用反射的 IllegalAccessException

ruby-on-rails - PostgreSQL "could not identify an equality operator for type json"的 Heroku 错误

eclipse - 使用 Eclipse 的 Hadoop 程序上的 JsonMappingException

java - writeValue 方法中的 Jackson 2.0 序列化配置

java - weblogic 中的 web 应用程序部署失败 : Proxy authentication failure

json - 将嵌套列表转换为 json 会产生多余的数组

javascript - 从 MySQL DATABASE(即多个表)创建 JavaScript 对象

java.lang.NoClassDefFoundError : com/google/api/client/json/JsonFactory issue