컨텍스트를 설정하기 위해 JSP에서는 다음과 같이 객체의 메소드에 액세스 할 수 있습니다.
Class Student
public Object getXXXWhichNeedsFewLogic() {
// Logic to get obj, which i don't want to store as a variable in this class.
return obj;
}
학생 객체를 jsp에 전달하면 다음과 같이이 메서드에 액세스 할 수 있습니다.
student.XXXWhichNeedsFewLogic
Gson 직렬화 중에 동일한 결과를 얻을 수 있습니까? 최종 출력 json은 다음과 같은 값을 포함해야합니다.
{XXXWhichNeedsFewLogic : obj}
다음은 메서드의 결과를 직렬화하기위한 샘플 클래스입니다.
public class GsonTest {
public static class Student {
public Object getXXXWhichNeedsFewLogic() {
return "foo";
}
}
public static class GetterSerializer<T> implements JsonSerializer<T> {
@Override
public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
if (null == src) {
return new JsonNull();
}
JsonObject obj = new JsonObject();
for (Method m : src.getClass().getDeclaredMethods()) {
if (m.getName().startsWith("get") && m.getParameterCount() == 0) {
try {
obj.add(m.getName().substring(3), context.serialize(m.invoke(src)));
} catch (InvocationTargetException | IllegalAccessException e) {
}
}
}
return obj;
}
}
@Test
public void testSerialization() {
System.out.println(
new GsonBuilder()
.registerTypeAdapter(Student.class, new GetterSerializer<Student>())
.create()
.toJson(new Student()));
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다