我正在尝试根据某些请求条件获取产品数据。当我使用转换器和填充器将productmodel转换为productdata时,我得到所有产品数据作为响应。
我曾尝试在将productmodel数据转换并填充为productdata时设置字符串值,但这无济于事!
{
"products": [
{
//Getting from Product Model
"name" : "ABC"
"desc" : "abcde"
"Quantity": 2"
//Not from Product Model
"matcode" : "001100"
},
]
}
是否可以在同一响应中再设置一个字符串值(String matcode ="ABC"
)?
答案 0 :(得分:1)
理想情况下,如果您在ProductData中正确设置matcode
(一个属性),它将反映在响应中
*beans.xml
中声明ProducctData中的Decare matcode 属性,诸如此类。
<bean class="de.hybris.platform.commercefacades.product.data.ProductData">
<!-- other attributes -->
<property name="matcode" type="java.util.Set<java.lang.String>"/>
</bean>
现在在填充器内部,设置matcode
属性值,即可完成操作。调试控制器,然后查看产品数据中是否存在自定义属性值。如果存在,它将被正确转换为JSON。
@Override
public void populate(final SOURCE productModel, final TARGET productData) throws ConversionException
{
//... other codes
productData.setMatcode("001100"); // add your logic to set this value
}
答案 1 :(得分:0)
如果您使用的是hql,则可以执行以下操作:
@Entity
@Table(name = "product")
public class Product {
@Column(name = "name")
private String name;
@Column(name = "desc")
private String desc;
@Column(name = "quantity")
private Integer quantity;
@Transient
@Column(name = "quantity")
private String matcode;
public Product(String name, String desc, Integer quantity, String matcode) {
this.name = name;
this.desc = desc;
this.quantity = quantity;
this.matcode = matcode;
}
}
如果您想了解有关Transient
注释的更多信息,请关注Transient Attribute
答案 2 :(得分:0)
您可以使用gson之类的库。 假设您具有这样的模型:
public class Products
{
private List<Product> products;
}
public class Product
{
private String name;
private String desc;
private String Quantity;
}
简便方法:
向产品模型添加另一个属性
private String matcode;
现在可以使用以下代码:
Gson gson = new Gson();
String jsonOutput = "{\"products\": [{ \"name\" : \"ABC\" ,\"desc\" : \"abcde\", \"Quantity\": \"2\"}]}";
Products products = gson.fromJson(jsonOutput, Products.class);
System.out.println(products);
for(Product p : products.getProducts()){
p.setMatcode("001100");
}
System.out.println(gson.toJson(products));
另一条更长的路径:
a。读取JSON回应 b。转换为对象(您应该已经在做) C。使用gson将对象转换为JsonElement作为数组 d。根据需要迭代和更新JsonObject e。将更新后的JsonElement转换为String输出。
下面的工作代码:
Gson gson = new Gson();
String jsonOutput = "{\"products\": [{ \"name\" : \"ABC\" ,\"desc\" : \"abcde\", \"Quantity\": \"2\"}]}";
Products products = gson.fromJson(jsonOutput, Products.class);
System.out.println(products);
JsonElement jsonElement = gson.toJsonTree(products);
JsonArray jsonArray = jsonElement.getAsJsonObject().get("products").getAsJsonArray();
for (JsonElement ele : jsonArray) {
JsonObject obj = ele.getAsJsonObject();
obj.addProperty("matcode", "001100");
}
String updatedJsonOutput = gson.toJson(jsonElement);
System.out.println("Updated json Object: " + updatedJsonOutput);