use of com.serotonin.json.spi.TypeResolver in project ma-core-public by infiniteautomation.
the class JsonReader method read.
/**
* Return an object of the given generic type that represents the given JSON value. This method can be used when the
* type to return is, say, List<MyObject>. To represent a specific type, use the TypeDefinition object.
*
* @param type
* the generic type of object to return
* @param jsonValue
* the JSON value from which to get object data
* @return the populated object
* @throws JsonException
*/
public Object read(Type type, JsonValue jsonValue) throws JsonException {
if (jsonValue == null)
return null;
Class<?> clazz = TypeUtils.getRawClass(type);
TypeResolver resolver = context.getResolver(clazz);
if (resolver != null) {
type = resolver.resolve(jsonValue);
clazz = TypeUtils.getRawClass(type);
}
ClassConverter converter = context.getConverter(clazz);
Object value = converter.jsonRead(this, jsonValue, type);
return value;
}
use of com.serotonin.json.spi.TypeResolver in project ma-core-public by infiniteautomation.
the class SubclassTest method main.
public static void main(String[] args) throws Exception {
JsonContext context = new JsonContext();
context.addResolver(new TypeResolver() {
@Override
public Class<?> resolve(JsonValue jsonValue) throws JsonException {
if (jsonValue.toJsonObject().containsKey("sub1Value"))
return Subclass1.class;
if (jsonValue.toJsonObject().containsKey("sub2Value"))
return Subclass2.class;
throw new JsonException("Unknown BaseClass: " + jsonValue);
}
}, BaseClass.class);
// context.addFactory(new ObjectFactory() {
// @Override
// public Object create(JsonValue jsonValue) throws JsonException {
// if (jsonValue.toJsonObject().hasProperty("sub1Value"))
// return new Subclass1();
// if (jsonValue.toJsonObject().hasProperty("sub2Value"))
// return new Subclass2();
// throw new JsonException("Unknown BaseClass: " + jsonValue);
// }
// }, BaseClass.class);
// List<BaseClass> list = new ArrayList<BaseClass>();
// list.add(new Subclass1());
// list.add(new Subclass2());
//
// String json = JsonWriter.writeToString(context, list);
//
// System.out.println(json);
String json = "[{\"id\":\"Subclass1\",\"sub1Value\":\"a\",\"baseValue\":\"b\"},{\"myId\":\"Subclass2\",\"sub2Value\":\"c\",\"baseValue\":\"d\"}]";
JsonReader reader = new JsonReader(context, json);
TypeDefinition type = new TypeDefinition(List.class, BaseClass.class);
Object read = reader.read(type);
System.out.println(read);
}
Aggregations