【问题标题】:how to get field name of class in java如何在java中获取类的字段名
【发布时间】:2016-02-12 09:48:13
【问题描述】:

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

这是我的代码:

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

【问题讨论】:

  • 您可以使用Gson 库代替json-simpleGson 可以将 JSON 字符串转换为 Java 对象,反之亦然
  • 你使用像jackson这样的json库吗?使用 jackson,您可以使用注释设置 MyCustomClass Pojo 以及应该解析哪些字段。
  • 这些答案对你有帮助吗?

标签: java json dynamic reflection field


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    使用 jackson 库,您可以直接使用 json 注释设置 Pojo,并且可以将 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>
    

    DocumentationExample

    【讨论】:

      【解决方案3】:

      你可以通过这个构造获得所有的类字段:

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

      你的班级是:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-19
        • 2014-08-06
        相关资源
        最近更新 更多