I'm trying to read contents of JSON arary in Java, and get each element as a JSON string. My attempts have failed.
Let's assume here is the base JSON:
{ "book": [
{ "category": "",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": ""
},
{ "category": "fiction",
"author": "",
"title": "Sword of Honour",
"price": "12.99"
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": "8.99"
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
]
}
And I iterate through the whole array, and need to get each element as JSON String (some properties can be empty). So first String would be:
{ "category": "",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": ""
}
What I did is this:
String response = Unirest.get(db).header("cache-control", "no-cache").asString().getBody();
int length = JsonPath.read(response, "$.book.length()");
System.out.println(length);
for (int i = 0; i < length; i++) {
String json = JsonPath.read(response, "$.book["+i+"]").toString();
System.out.println("1111111\n"+json);
process(json);
}
But what I get is messy, and not the same string. It doesn't include ""
.
What is the solution?