/* package whatever; // don't place package name! */
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
class Ideone {
String json
= "{\"id\":1, \"name\":\"jsmith\"}"; NaiveObjectMapper objectMapper = new NaiveObjectMapper();
User user = objectMapper.readValue(json, User.class);
}
public static class NaiveObjectMapper {
private Map
<String, Object
> fieldsAndMethods
; private NaiveJsonParser parser;
public <T
> T readValue
(String content, Class
<T
> valueType
) { parser = new NaiveJsonParser(content);
try {
// aggregate all value type fields and methods inside a map
fieldsAndMethods = new HashMap<>();
for (Field field
: valueType.
getDeclaredFields()) { fieldsAndMethods.put(field.getName(), field);
}
for (Method method
: valueType.
getMethods()) { fieldsAndMethods.put(method.getName(), method);
}
// create an instance of value type by calling its default constructor
Constructor<T> constructor = valueType.getConstructor();
// loop through all json nodes
while ((propName = parser.nextFieldName()) != null) {
// find the corresponding field
Field prop
= (Field) fieldsAndMethods.
get(propName
); // get and set field value
deserializeAndSet(prop, bean);
}
return (T) bean;
e.printStackTrace();
e.printStackTrace();
e.printStackTrace();
e.printStackTrace();
}
return null;
}
private void deserializeAndSet
(Field prop,
Object bean
) { Class<?> propType = prop.getType();
Method setter
= (Method) fieldsAndMethods.
get(getFieldSetterName
(prop
)); try {
if (propType.isPrimitive()) {
if (propType.getName().equals("int")) {
setter.invoke(bean, parser.getIntValue());
}
} else if (propType
== String.
class) { setter.invoke(bean, parser.getTextValue());
}
e.printStackTrace();
e.printStackTrace();
}
}
String propName
= prop.
getName(); return "set" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
}
}
static class NaiveJsonParser {
int currentNodeIdx = -1;
public NaiveJsonParser
(String content
) { // split the content into 'property:value' nodes
nodes = content.replaceAll("[{}]", "").split(",");
}
public String nextFieldName
() { if ((++currentNodeIdx) >= nodes.length) {
return null;
}
String[] propertyAndValue
= nodes
[currentNodeIdx
].
split(":"); currentProperty = propertyAndValue[0].replace("\"", "").trim();
currentValueStr = propertyAndValue[1].replace("\"", "").trim();
return currentProperty;
}
public String getTextValue
() { return String.
valueOf(currentValueStr
); }
public int getIntValue() {
return Integer.
valueOf(currentValueStr
).
intValue(); }
}
public static class User {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
return name;
}
public void setName
(String name
) { this.name = name;
}
@Override
return "id = " + id + ", name = \"" + name + "\"";
}
}
}