Skip to content

Commit

Permalink
Adding JsonNode Function
Browse files Browse the repository at this point in the history
  • Loading branch information
akashtayal committed Mar 4, 2023
1 parent 9f19cd0 commit 115a0fb
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
25 changes: 25 additions & 0 deletions API JsonNode Functions/JsonNodeReader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.learning.api.jsonnode;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonNodeReader {

public JsonNode readJsonFromString(String json) throws IOException {

ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readTree(json);
}

public JsonNode readJsonFromFile(File file) throws IOException {

ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readTree(file);
}



}
40 changes: 40 additions & 0 deletions API JsonNode Functions/ReadingFromJsonNode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.learning.api.jsonnode;

import java.util.Iterator;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;

public class ReadingFromJsonNode {

String str;
/*
* It is very useful when you don't know the about Json what it looks like.
*
* Add operations as per your need.
*/
public void traverseJson(JsonNode node) {

if(node.isArray()) {
ArrayNode arrayNode = (ArrayNode) node;
for(int index=0;index<arrayNode.size();index++) {
traverseJson(arrayNode.get(index));
}
}
else if(node.isObject()) {
Iterator<String> fieldNames= node.fieldNames();

while(fieldNames.hasNext()) {
str = fieldNames.next();
System.out.println(str); // -------Printing the Field --------- //
traverseJson(node.get(str));
}
}
else {
System.out.println(node.asText()); // ------Printing the field values--------//
}

}


}

0 comments on commit 115a0fb

Please sign in to comment.