Search in sources :

Example 1 with JsonEntityFieldMakerImpl

use of org.nutz.json.impl.JsonEntityFieldMakerImpl in project nutz by nutzam.

the class JsonEntityTest method test_entity_field_maker.

@Test
public void test_entity_field_maker() {
    Json.clearEntityCache();
    JENObj obj = new JENObj();
    obj.setAge(100);
    obj.setName("name");
    obj.setObjId(9l);
    Json.setDefaultFieldMaker(new AbstractJsonEntityFieldMaker() {

        @Override
        public JsonEntityField make(Mirror<?> mirror, Method method) {
            return null;
        }

        @Override
        public JsonEntityField make(Mirror<?> mirror, Field field) {
            return null;
        }
    });
    assertEquals("{}", Json.toJson(obj, JsonFormat.compact()));
    Json.clearEntityCache();
    Json.setDefaultFieldMaker(new AbstractJsonEntityFieldMaker() {

        @Override
        public JsonEntityField make(Mirror<?> mirror, Method method) {
            if (method.getName().equals("setName")) {
                String fn = Strings.lowerFirst(method.getName().substring(3));
                return JsonEntityField.eval("another_name", method.getParameterTypes()[0], mirror.getEjecting(fn), new InjectBySetter(method));
            }
            return null;
        }

        @Override
        public JsonEntityField make(Mirror<?> mirror, Field field) {
            return JsonEntityField.eval("test_" + field.getName(), field.getType(), mirror.getEjecting(field), mirror.getInjecting(field.getName()));
        }
    });
    String json = Json.toJson(obj, JsonFormat.compact());
    assertTrue(json.contains("\"test_objId\":9"));
    assertTrue(json.contains("\"test_name\":\"name\""));
    assertTrue(json.contains("\"test_age\":100"));
    assertTrue(json.contains("\"another_name\":\"name\""));
    Json.clearEntityCache();
    Json.setDefaultFieldMaker(new JsonEntityFieldMakerImpl());
}
Also used : JsonEntityField(org.nutz.json.entity.JsonEntityField) Field(java.lang.reflect.Field) JENObj(org.nutz.json.meta.JENObj) JsonEntityField(org.nutz.json.entity.JsonEntityField) InjectBySetter(org.nutz.lang.inject.InjectBySetter) JsonEntityFieldMakerImpl(org.nutz.json.impl.JsonEntityFieldMakerImpl) Method(java.lang.reflect.Method) Test(org.junit.Test)

Aggregations

Field (java.lang.reflect.Field)1 Method (java.lang.reflect.Method)1 Test (org.junit.Test)1 JsonEntityField (org.nutz.json.entity.JsonEntityField)1 JsonEntityFieldMakerImpl (org.nutz.json.impl.JsonEntityFieldMakerImpl)1 JENObj (org.nutz.json.meta.JENObj)1 InjectBySetter (org.nutz.lang.inject.InjectBySetter)1