Wednesday, January 8, 2014

Converting map to JSON String using Jackson API


API libraries can found here @ http://jackson.codehaus.org/

Example:

import java.util.ArrayList;
import java.util.HashMap;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MapToJSONExample {

public static void main(String[] args) {
               
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("param1", "Hyderabad");
hashMap.put("param2", "Bangalore");

ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("hello1");
arrayList.add("hello2");
arrayList.add("hello3");

Employee employee = new Employee("Kondal", "Kolipaka");

ObjectMapper mapper = new ObjectMapper();
String writeValueAsString;
try {
writeValueAsString = mapper.writeValueAsString(hashMap);
System.out.println(writeValueAsString);

writeValueAsString = mapper.writeValueAsString(arrayList);
System.out.println(writeValueAsString);

writeValueAsString = mapper.writeValueAsString(employee);
System.out.println(writeValueAsString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}


public class Employee {

private String firstName;
private String lastName;

public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}

/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}

}

Output:
{"param1":"Hyderabad","param2":"Bangalore"}
["hello1","hello2","hello3"]
{"firstName":"Kondal","lastName":"Kolipaka"}


Just to conclude, we can use writeValueAsString(Object obj) method for any bean class which can be serializable.

Say for example, if you remove getters from Employee class, it will be throwing JsonMappingException.

No serializer found for class Employee and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.SerializationFeature.FAIL_ON_EMPTY_BEANS) )

No comments:

Post a Comment