繁体   English   中英

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

[英]how to get field name of class in java

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

这是我的代码:

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);
    }
}

怎么做?

*杰森字段名称= MycustomClass字段名称

杰克逊格森将为您完成所有这一切。

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));
}

使用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字符串

您可以这样调用方法:

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>

文档示例

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

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

与您的班级是:

MyCustomClass temp = new MyCustomClass();
Field[] methods = temp.getFields();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM