Reputation: 7394
I have a input json object that contains a array as shown below:
[{"key11":"value11","key12":"value12"},
{"key21":"value21","key22":"value22"},
...
{"keyn1":"valuen1","keyn2":"valuen2"}]
I would like to use jackson parser ,firstly, to identify the number of rows and secondly, print only the values on the screen. I want it to be as lightweight as possible. Can anyone point me to a direction?
Upvotes: 3
Views: 16572
Reputation: 19211
Assuming that a row
is one of the entries in a ArrayNode
the following simple approach may be useful. It uses the JsonNode
abstraction instead of a series of nested Map
objects which I personally prefer since JsonNode
provides a series of utility methods that are helpful when dealing with this kind of data (data where the structure is possibly unknown or very dynamic so that it can't be easily transformed to a POJO).
The testcase below illustrates how to find the number of rows and how to print the values. To get hold of the values the method JsonNode.elements()
is used and the number of rows is simply a call to the size()
-method.
public class ArrayNodeTest {
@Test
public void verifySizeAndPrintRows() throws IOException {
final String jsonStr =
"[{\"key11\":\"value11\",\"key12\":\"value12\"},\n" +
"{\"key21\":\"value21\",\"key22\":\"value22\"},\n" +
"{\"keyn1\":\"valuen1\",\"keyn2\":\"valuen2\"}]";
final ObjectMapper mapper = new ObjectMapper();
final JsonNode jsonNode = mapper.readTree(jsonStr);
// Verify size
Assert.assertEquals(3, jsonNode.size());
// And print rows
for (final JsonNode row : jsonNode) {
final Iterable<JsonNode> iterable = () -> row.elements();
iterable.forEach(elem -> System.out.println(elem.asText()));
}
}
}
Upvotes: 5
Reputation: 66943
to identify the number of rows
What's a "row"? Is a key/value pair a row? Is an element of the JSON array (no matter how many key/value pairs it contains) a row?
print only the values on the screen
Jackson has nothing to do with printing anything on any screens. Jackson can be used to populate a Java data structure from the input JSON, and the populated Java data structure can then be used however you want.
Given the JSON structure in the original question, a simple solution would be to bind to a list (or array) of maps, and then just iterate through the list of maps, accessing all of the values. Following is such an example.
import java.io.File;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonFoo
{
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper();
Map<String, String>[] maps = mapper.readValue(new File("input.json"), Map[].class);
for (Map<String, String> map : maps)
{
for (Map.Entry<String, String> entry : map.entrySet())
{
System.out.println(entry.getValue());
}
}
}
}
Output:
value11
value12
value21
value22
valuen1
valuen2
Upvotes: 0