Skip to content

Instantly share code, notes, and snippets.

@jvmvik
Last active December 30, 2015 21:09
Show Gist options
  • Save jvmvik/7885446 to your computer and use it in GitHub Desktop.
Save jvmvik/7885446 to your computer and use it in GitHub Desktop.
Convert a POJO to a JsonObject (GSON 2.4 library...)
package io.milkyway.mongo.json;
import com.google.gson.JsonObject;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Bean to Json helps to produce a JSON from any POJO.
* <p/>
* Look at the template for example.
*
* @author jvmvik
*/
public class BeanToJson
{
public static JsonObject convert(Serializable bean) throws IntrospectionException
{
JsonObject json = new JsonObject();
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();
if (properties == null)
return json;
// copy properties into hashtable
for (PropertyDescriptor property : properties)
{
Class paramClass = property.getPropertyType();
Method getter = property.getReadMethod();
try
{
Object paramValue = getter.invoke(bean);
if (paramValue != null)
{
// converts getBookTitle() to book_title
String paramName = property.getName();
paramName = splitCamelCase(paramName);
if (!(paramValue instanceof String))
json.addProperty(paramName, (String)paramValue); // Good job json smart
//TODO Add support for other type...
}
} catch (InvocationTargetException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
return json;
}
public static String splitCamelCase(String s)
{
return s.replaceAll(
String.format("%s|%s|%s",
"(?<=[A-Z])(?=[A-Z][a-z])",
"(?<=[^A-Z])(?=[A-Z])",
"(?<=[A-Za-z])(?=[^A-Za-z])"
),
"_"
).toLowerCase();
}
}
package io.milkyway.mongo;
import com.google.gson.JsonObject;
import io.milkyway.mongo.json.BeanToJson;
import org.junit.Before;
import org.junit.Test;
import java.beans.IntrospectionException;
import java.io.Serializable;
import static org.junit.Assert.assertEquals;
/**
* BeanToJson test...
*
* TODO This may need some minor ajustement...
* @author jvmvik
*/
public class BeanToJsonTest
{
@Before
public void setUp() throws Exception
{
}
@Test
public void convertSimple() throws IntrospectionException
{
SimpleCat cat = new SimpleCat();
JsonObject json = BeanToJson.convert(cat);
String result = json.toString();
assertEquals("{\"head_size\":10.314156,\"weight\":3,\"friends\":10.314156,\"age\":1,\"length\":2,\"gender\":{},\"single_byte\":1,\"alive\":true}", result);
}
@Test
public void convertClass() throws IntrospectionException
{
Cat cat = new Cat();
JsonObject json = BeanToJson.convert(cat);
String result = json.toString();
assertEquals("{\"head_size\":10.314156,\"weight\":3,\"friends\":10.314156,\"name\":\"kitty\",\"age\":1,\"length\":2,\"gender\":{},\"single_byte\":1,\"alive\":true}", result);
}
public class SimpleCat implements Serializable
{
private boolean alive;
private long length;
private short weight;
private int age;
private double friends;
private float headSize;
private char gender;
private byte singleByte;
public SimpleCat()
{
alive = true;
weight = 3;
age = 1;
length = 2L;
headSize = 10.314156F;
gender = 'M';
singleByte = 1;
friends = 10.314156D;
}
public boolean getAlive()
{
return alive;
}
public void setAlive(boolean alive)
{
this.alive = alive;
}
public long getLength()
{
return length;
}
public void setLength(long length)
{
this.length = length;
}
public short getWeight()
{
return weight;
}
public void setWeight(short weight)
{
this.weight = weight;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public double getFriends()
{
return friends;
}
public void setFriends(double friends)
{
this.friends = friends;
}
public float getHeadSize()
{
return headSize;
}
public void setHeadSize(float headSize)
{
this.headSize = headSize;
}
public char getGender()
{
return gender;
}
public void setGender(char gender)
{
this.gender = gender;
}
public byte getSingleByte()
{
return singleByte;
}
public void setSingleByte(byte singleByte)
{
this.singleByte = singleByte;
}
}
/**
* Simple class that model a Cat
*/
public class Cat implements Serializable
{
private Boolean alive;
private Character gender;
private Short weight;
private Integer age;
private Long length;
private Float headSize;
private String name;
private Byte singleByte;
private Double friends;
public Cat()
{
alive = true;
weight = 3;
length = 2L;
headSize = 10.314156f;
gender = 'M';
singleByte = 1;
friends = 10.314156D;
name = "kitty";
age = 1;
}
public Boolean getAlive()
{
return alive;
}
public void setAlive(Boolean alive)
{
this.alive = alive;
}
public Character getGender()
{
return gender;
}
public void setGender(Character gender)
{
this.gender = gender;
}
public Short getWeight()
{
return weight;
}
public void setWeight(Short weight)
{
this.weight = weight;
}
public Integer getAge()
{
return age;
}
public void setAge(Integer age)
{
this.age = age;
}
public Long getLength()
{
return length;
}
public void setLength(Long length)
{
this.length = length;
}
public Float getHeadSize()
{
return headSize;
}
public void setHeadSize(Float headSize)
{
this.headSize = headSize;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Byte getSingleByte()
{
return singleByte;
}
public void setSingleByte(Byte singleByte)
{
this.singleByte = singleByte;
}
public Double getFriends()
{
return friends;
}
public void setFriends(Double friends)
{
this.friends = friends;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment