如何在java中动态创建JSON?
我与getter和setter有一个客户关系示例客户关系是
customerEntity =
{
"customerNumber": "1234",
"firstName": "Test",
"email": "test@gmail.com",
"id": "1",
"middleName": "doe",
"phone": "11111"
}
我有JsonProperty的java类属性和getter和setter,如下所示
Attributes =
{
"name": "string"
"value": "string"
}
我有一个包含Customerntiy随机元素的列表,例如:
List<String> stringlist = { "firstName" , "phone"}
我已经创建了一个类型属性列表
List<Attributes> Attributeslist = new ArrayList<>();
我想创建stringlist中所有元素的Attributelist,例如:
Attributeslist =[
{
"name": "firstName"
"value": "Test"
},
{
"name": "phone"
"value": "11111"
}
]
为此,我编写了如下代码,但在previewattributes.setValue();
中传递什么,因为该值取决于下面For循环中的mystring
。在这个例子中,对于不同的迭代,它将是previewattributes.setValue(customerEntity.getFirstName());
和previewattributes.setValue(customerEntity.getPhone());
,但是我如何编码它呢
for (String mystring : stringlist) {
Attributes previewattributes;
previewattributes = new Attributes();
previewattributes.setName(mystring);
previewattributes.setValue(value here would be of customerentity);
Attributeslist.add(previewattributes);
}
客户身份:
@Entity
@Table(name = "Customer_tbl")
public class CustomerEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long rowId;
@Column(name = "customer_number")
private String customerNumber;
public String getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}
}
# 1 楼答案
可以在Java中使用反射。 更简单的方法是将customerEntity存储在HashMap中并从中获取
和内部for循环:
# 2 楼答案
如果我对你的理解正确,你有一个客户Json数组,你想在其中分离一些属性,请检查下面的代码
}
输出