Haozhun
Haozhun

Reputation: 6521

Jackson: partial JSON parsing, read arbitrary value as String

I'm using Jackson streaming API. I want to parse certain values as json strings.

For example, I have

[
    5,
    "a",
    {"c": "d"}
]

I want to parse it and return an array of 3 Strings, each containing a JSON string.

["5", "\"a\"", "{\"c\": \"d\"}"]

I found JsonParser.readValueAsTree. And I assume a TreeNode can be turned into a java String representation of the json node. I don't know if this is the right way to go. If it is, how do I turn a TreeNode into a String?

Upvotes: 3

Views: 3198

Answers (2)

Haozhun
Haozhun

Reputation: 6521

Sorry. I probably didn't ask my question in a clear enough manner.

I needed to read "arbitrary value" as string. In the example, I gave an array. But I also need my code to work with map, number, or string.

Also, I mentioned I was using Jackson streaming API in the question. Given the amount of existing code, I can't change to other Jackson APIs.

The solution to my own question is:

OBJECT_MAPPER.writeValueAsString(parser.readValueAsTree())

where

JsonFactory JSON_FACTORY = new JsonFactory();
ObjectMapper OBJECT_MAPPER = new ObjectMapper(JSON_FACTORY);
JsonParser parser = JSON_FACTORY.createParser(...);

Upvotes: 2

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279990

You basically want a JSON array consisting of the JSON representation of the values in your original JSON array.

There's no direct conversion. A JSON number will be treated as a Java Number (depending). A JSON string will be treated as a Java String. A JSON object will be treated as a Java LinkedHashMap or some custom POJO type. (A JSON array will be treated as a Collection type.)

However, you can do the conversion yourself. Start by parsing the JSON into a ArrayNode (of JsonNode values). Then extract each value from the ArrayNode and generate a TextNode from their JSON representation

For example

ObjectMapper mapper = new ObjectMapper();
ArrayNode originalNode = mapper.readValue(theJson, ArrayNode.class);

ArrayNode newNode = mapper.getNodeFactory().arrayNode(); // new array 
for (JsonNode value : originalNode) {
    TextNode textNode = new TextNode(value.toString());
    newNode.add(textNode);
}

System.out.println(newNode);

prints

["5","\"a\"","{\"c\":\"d\"}"]

Upvotes: 4

Related Questions