嵌套为每个循环以在json对象中存储数据

时间:2014-12-08 11:34:24

标签: java json

我试图以下面的格式将数据存储到json对象中:

{"mobile:":[{"price":"Rs. abc","name":"def"},{"price":"Rs. ghi","name":"jkl"},....}]}

我正在尝试以下方式,但我没有获得所需的输出代码如下:

Elements mobilename = document.select(
"#products div.product-unit div.pu-title ");
Elements price = document.select(
"#products div.product-unit div.pu-price div.pu-final span.fk-font-17");

for(Element url1:mobilename)
{
text=url1.text();
System.out.println(text);
for(Element b:price)
{
    text1= b.text();

    System.out.println(text1);

    arr1.add(text1);
    arr1.add(text);
}

pa.put("price",text1 );
pa.put("name", text);
obj7.add(pa);
}
json.put("mobile:", obj7);  

我在所有阵列中获得相同的手机名称和价格。

谢谢。

1 个答案:

答案 0 :(得分:0)

我会使用杰克逊映射器。你可以找到它here

import com.fasterxml.jackson.databind.ObjectMapper;

public static class YourObject {
    private List<Mobile> mobile;
    // add getter + setter for mobile
}

public static class Mobile {
    private String price;
    private String name;
    // add getter+setter for price and name
}

YourObject obj = new YourObject();
obj.setMobile(new Mobile[] { new Mobile("price1", "name1"), new Mobile("price2", "name2") });

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(obj);