如何在 java 中获取 class 的字段名称
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);
}
}
怎么做?
*jason 字段的名称 = MycustomClass 字段的名称
你可以用这个结构得到所有的class字段:
Class class = ...//obtain class object
Field[] methods = class.getFields();
你的 class 是:
MyCustomClass temp = new MyCustomClass();
Field[] methods = temp.getFields();
使用 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
- 是你的对象并且return类型
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>
Documentation and Example
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));
}
大家好抱歉我的语言不好!
这是我的代码:
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 字段的名称
你可以用这个结构得到所有的class字段:
Class class = ...//obtain class object
Field[] methods = class.getFields();
你的 class 是:
MyCustomClass temp = new MyCustomClass();
Field[] methods = temp.getFields();
使用 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
- 是你的对象并且return类型
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>
Documentation and Example
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));
}