6

I'm writing an android app that requires binding a JSON object into a domain entity with the keys from the JSON as instance variables. Since there are several domain entities, each with different instance variables that the JSON needs to bind to in the app, i'd like to write a method such as ths following:

  1. Loop through all the instance variables from the domain
  2. if a key exists in the JSON with the name of the instance variable, take the value for this key from the JSON and set the Domain's instance variable with this key name equal to this value.

The reason i'm interested in the doing the binding from the class to the JSON is because if the JSON changes for some reason, I don't want it to break the app when the instance variable doesn't exist in the app's domain for a specific JSON key.

Thanks in advance for any help!

asked Nov 5, 2010 at 1:06

2 Answers 2

5

Most likely you want to use a json library that does this for you. Jackson is a good one that is also used by Spring MVC.

To answer your question, you can use getDeclaredFields() on a class, and use java.lang.reflect.Modifier.isStatic() to check if the field is static.

private static class Foo {
 private static long car;
 private int bar;
 private String baz;
}
public static void main(String[] args) {
 for (Field field : Foo.class.getDeclaredFields()) {
 if (!Modifier.isStatic(field.getModifiers())) {
 System.out.println("Found non-static field: " + field.getName()); 
 }
 }
}

This will print out:

Found non-static field: bar
Found non-static field: baz
answered Nov 5, 2010 at 2:14
0

oksayt's answer is correct, but I'd take it with a grain of salt. Not every field holds a property that should be exposed publically. The mechanism to use is the Java Beans Introspector. You can use my answers to these previous Questions as reference:

Additional Reference:

answered Nov 5, 2010 at 10:48
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.