Convert Json to String and String to Json (java)


Technologies used :
  java,jackson Object mapper jar .


For Object mapper we are using following jar .



org.codehaus.jackson

Example : 


public class MappperExmples
{
    public static void main( String[] args ) throws IOException
    {
    ObjectMapper mapper = new ObjectMapper();
    User user = getUser();
   
    //Object to JSON in file
    // mapper.writeValue(new File("c:\\user.json"), user);

    //Object to JSON in String
    String stringVal = mapper.writeValueAsString(user);
    System.out.println(stringVal);
   
    //JSON from file to Object
    //User userObj = mapper.readValue(new File("c:\\user.json"), User.class);
   
    //JSON from String to Object
    User userObj = mapper.readValue(stringVal, User.class);
    System.out.println(userObj.getAddress().getCity());
   
    UserView userView = new UserView();
    userView.setId(1234L);
    userView.setGeneder("M");
    userView.setName("Test USer View");
   
    //By default all fields without explicit view definition are included, disable this
    mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);

   
    //display name only
String idOnly = mapper.writerWithView(Views.IdOnly.class).writeValueAsString(userView);
String idAndName = mapper.writerWithView(Views.IdAndName.class).writeValueAsString(userView);

System.out.println("idOnly :: "+idOnly);
System.out.println("idAndName :: "+idAndName);


Map<String, Object> map = new HashMap<String, Object>();
map = mapper.readValue(idAndName, new TypeReference<Map<String, String>>(){});
System.out.println("****Map output****");
System.out.println(map);


//mapper.writeValue(new File("c:\\user.json"), map);

String stringMap = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
System.out.println(stringMap);


   
    }

/**
* @return User
*/
private static User getUser() {
User user = new User();
    user.setId(1234L);
    user.setGeneder("M");
    user.setName("Test User");
    Address address  = new Address();
    address.setCity("Hyderabad");
    address.setState("AP");
    user.setAddress(address);
return user;
}
}


Download : 

https://drive.google.com/open?id=1AmUIj2MOxP35OaiX5hAonN1N6HvoRKwt




0 Response to "Convert Json to String and String to Json (java)"

Post a Comment