有没有办法将字符串读入Jackson API以轻松获取JSON对象

时间:2013-11-12 04:27:25

标签: java json jackson

是否有办法将String传递给某些Jackson对象并让它为我填充JSON obj?也许我正在比较苹果和橙子,但json-rpc-1.0.jar库允许我这样做:

// string will be read in from file but putting the string below just to show what i'm trying to do.
JSONObject jsonObj; 
String testStr = "{"blah":123, "aaa": "got here", "foo":"bar", "bar":123}";
jsonObj = new JSONObject(testStr);
jsonObj.put("blah",345);

如果我执行

System.out.println(jsonObj);

我明白了:

{"blah":345, "aaa": "got here", "foo":"bar", "bar":123}

json-rpc-1.0.jar文件的问题是它与long基元类型不能很好地配合。出于某种原因,如果我尝试将时间戳(长数据类型)分配给字段,它会将长数据转换为类似1.32e9的内容。

我发现Jackson(jackson-core-2.2.3.jar)的长度更好,保留了我的时间戳所需的10-13位数字。但是,我找不到任何像杰克逊上面的代码片段一样的东西。最接近的可能是ObjectMapper.readValue,但它不完全像上面那样。

如果可能,或者我只是在做梦,请告诉我。在此先感谢您的帮助。与此同时,我将尝试更多地查看API。

1 个答案:

答案 0 :(得分:2)

IMO并不是杰克逊的意图。对于杰克逊,一个对象应该与其类的字段序列化。之后您不应该向该JSON添加任何内容。然而,为了这个问题,这是你能做的。举个例子

public static void main(String[] args) throws Exception {       
    ObjectMapper mapper = new ObjectMapper();
    MyClass a = new MyClass();
    ObjectNode node = mapper.<ObjectNode>valueToTree(a);
    node.put("blah", "123");
    System.out.println(node);
}

static class MyClass {
    private String value = "some text";
    private long timestamp = System.currentTimeMillis();
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public long getTimestamp() {
        return timestamp;
    }
    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }
}

打印

{"value":"some text","timestamp":1384233053765,"blah":"123"}

valueToTree()方法会将您的对象转换为ObjectNode,它是一种包含各种JSON元素的树。您可以通过添加或删除元素来修改此ObjectNode。这就是我们对node.put("blah", "123");所做的事情。它将添加一个名为blah且值为"123"的Json对象。