I get the below json from a url:
{"bytes": 5043, "name": "a", "timestamp": "11-Apr-2017 12:11:51", "ds": "Lab1"}
{"bytes": 0, "name": "b", "timestamp": "11-Apr-2017 12:11:51", "ds": "Lab1"}
{"bytes": 11590, "name": "c", "timestamp": "11-Apr-2017 12:11:51", "ds": "Lab1"}
I want to return the bytes for each line. Using Jackson I've tried parsing it as follows(note: json is saved to file for testing):
package JsonRead;
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTreeModelLogStorage {
public static void main(String[] args) {
try{
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(new File("JsonRead/json2.json"));
JsonNode logStorageNode = root;
for(JsonNode node : logStorageNode){
String bytesUsed = node.path("bytes").asText();
System.out.println("Bytes Used: " + bytesUsed);
}
} catch(IOException e){
System.out.println("IO Exception " + e );
}
}
}
This returns the following:
Bytes Used:
Bytes Used:
Bytes Used:
Bytes Used:
If I then change my for loop to the following I can see I'm returning the first line of json:
for(JsonNode node : logStorageNode){
String json = node.asText();
System.out.println("json: " + a);
}
How do I real the bytes for all lines of json?
Thanks guys. That was a big help.
I edited the try slightly to suit my needs. Here's what I ended up with:
ObjectMapper mapper = new ObjectMapper();
try(
FileReader reader = new FileReader("JsonRead/json2.json");
BufferedReader bufferedReader = new BufferedReader(reader);
) {
String currentLine;
while((currentLine=bufferedReader.readLine()) != null) {
Vault vlt = mapper.readValue(currentLine, Vault.class);
System.out.println(vlt.getBytes());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With