如何在java中获取类的字段名称

时间:2015-11-11 10:06:12

标签: java json dynamic reflection field

大家好抱歉我的语言不好!

这是我的代码:

MyCustomClass temp = new MyCustomClass();
for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject obj = jsonarray.getJSONObject(i);
    temp.ID = obj.getInt("ID");
    temp.PicName = obj.getString("PicName");
    temp.PicURL = obj.getString("PicURL");
    Items.add(temp);
}

我想采取这种动态

像这样的东西

MyCustomClass temp = new MyCustomClass();
Field[] myFields= MyCustomClass.class.getFields();
for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject obj = jsonarray.getJSONObject(i);
    for(int j=0;j<myFields.lenghth();j++)
    {
        myFields[j]=obj.getString(myFields[j].toString());
        Items.add(temp);
    }
}

怎么做?

* jason fields的名称= MycustomClass字段的名称

3 个答案:

答案 0 :(得分:3)

JacksonGson会为您完成所有这些。

static class TestClass {
    public int id;
    public String name;
}

@Test
public void gson() {
    Gson gson = new Gson();
    TestClass[] item = gson.fromJson("[{'id': 1, 'name': 'testclass'}]", TestClass[].class);
    assertThat(item[0].id, is(1));
    assertThat(item[0].name, is("testclass"));
    assertThat(item.length, is(1));
}

@Test
public void jackson() throws IOException {
    ObjectMapper jacksonObjectMapepr = new ObjectMapper();
    TestClass[] item = jacksonObjectMapepr.readValue("[{\"id\": 1, \"name\": \"testclass\"}]", TestClass[].class);
    assertThat(item[0].id, is(1));
    assertThat(item[0].name, is("testclass"));
    assertThat(item.length, is(1));
}

但是,要回答您的问题,您可以使用getDeclaredField查找每个字段。但是你必须做一些工作才能处理所有的类型映射。

@Test
public void sillyWayIDontRecommend() throws NoSuchFieldException, IllegalAccessException {
    TestClass[] item = new TestClass[1];

    JsonArray array = new JsonParser().parse("[{\"id\": 1, \"name\": \"testclass\"}]").getAsJsonArray();
    for(int i = 0; i<array.size(); i++) {
        item[i] = new TestClass();

        JsonObject object = array.get(i).getAsJsonObject();
        for(Map.Entry<String, JsonElement> entry : object.entrySet()) {
            Field field = TestClass.class.getDeclaredField(entry.getKey());
            if(field.getType().equals(int.class)) {
                field.setInt(item[i], entry.getValue().getAsInt());
            } else {
                field.set(item[i], entry.getValue().getAsString());
            }
        }
    }

    assertThat(item[0].id, is(1));
    assertThat(item[0].name, is("testclass"));
    assertThat(item.length, is(1));
}

答案 1 :(得分:2)

使用jackson库,您可以直接使用json注释设置Pojos,并且可以将JSON字符串直接转换为java对象。

解析的一般方法可以是这样的:

public static <T> T deserialize(T t, Class<T> clazz, String json) throws JsonParseException, JsonMappingException, IOException{
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(json, clazz);
    }

T - 是你的对象和返回类型

clazz - 是你的Pojo

json - 是你的json String

您可以调用以下方法:

MyCustomClass myCustomClass= new MyCustomClass();
myCustomClass= JsonUtil.deserialize(myCustomClass, MyCustomClass.class, json);

您的Pojo可能如下所示:

@JsonIgnoreProperties // ignores properties from json String which are not in your Pojo
public class MyCustomClass {

    @JsonProperty("anotherNameIfFieldNameIsNotEqual")
    private String picName;
    private String picURL;

    public String getPicName() {
        return picName;
    }
    public void setPicName(String picName) {
        this.picName = picName;
    }
    public String getPicURL() {
        return picURL;
    }
    public void setPicURL(String picURL) {
        this.picURL= picURL;
    }
}

这是你需要的maven依赖:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

DocumentationExample

答案 2 :(得分:1)

您可以使用此结构获取所有类字段:

String a = "9.8.0.0.10";
String b = "10.0.0.0.11";
String convertRegexp = "(^[0-9]{1,2}\\.[0-9]+)\\..*";        

double aAsDouble = Double.parseDouble(a.replaceAll(convertRegexp, "$1"));
double bAsDouble = Double.parseDouble(b.replaceAll(convertRegexp, "$1"));

if(aAsDouble > bAsDouble)

上课了:

Class class = ...//obtain class object
Field[] methods = class.getFields();