程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

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

发布于2021-10-01 03:33     阅读(1178)     评论(0)     点赞(21)     收藏(2)


大家好,对不起,我的语言不好!

这是我的代码:

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 字段的名称


解决方案


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


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.javaheidong.com/blog/article/293125/3d9a4db814f916095f7a/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

21 0
收藏该文
已收藏

评论内容:(最多支持255个字符)