Created
February 19, 2015 01:14
-
-
Save vajja/632f1e2ec29268397b8c to your computer and use it in GitHub Desktop.
Json Parsing in Java using marven library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package vajja; | |
| import vajja.User; | |
| // the old namespace mentioned in the original tutorial is outdated | |
| //import org.codehaus.jackson.map.ObjectMapper; | |
| import com.fasterxml.jackson.core.JsonParseException; | |
| import com.fasterxml.jackson.databind.JsonMappingException; | |
| import com.fasterxml.jackson.databind.ObjectMapper; | |
| import com.fasterxml.jackson.databind.DeserializationFeature; | |
| import java.io.File; | |
| import java.net.URL; | |
| import java.io.IOException; | |
| public class UserTest { | |
| public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { | |
| //Here we are taking the input from the json file and extracting the data | |
| File jsonFile = new File("user.json"); | |
| //This is the command to get data from the url | |
| URL jsonUrl = new URL("https://gist.githubusercontent.com/vajja/bf13481f31209d0b9f9c/raw/aba5d0ec9345b886426ab767376b7c9cb60c251f/user.json"); | |
| //Here we are declaring complete data as string and then extracting into normal daat | |
| String jsonStr = | |
| "{\"name\":{\"first\":\"Joe\",\"last\":\"Sixpack\"},\"gender\":\"MALE\",\"verified\":false,\"userImage\":\"Rm9vYmFyIQ==\"}"; | |
| User user = null; | |
| //convert java to json and viseversa | |
| ObjectMapper mapper = new ObjectMapper(); | |
| mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); | |
| //Here we are reading the json file to user | |
| user = mapper.readValue(jsonFile, User.class); | |
| //user.getName().getFirst() first it reads name and then goes to firstname and gives Joe | |
| System.out.println(user.getName().getFirst()); | |
| //this command retrieves the gender from the prints in the output | |
| System.out.println(user.getGender()); | |
| //Here the data is taken from the Url data | |
| user = mapper.readValue(jsonUrl, User.class); | |
| //We are retrieving the data similar to the json file | |
| System.out.println(user.getName().getLast()); | |
| //Here we are getting the data from the String jsonString declared above and printing the output | |
| user = mapper.readValue(jsonStr, User.class); | |
| System.out.println(user.getGender()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment