json转换求和问题

product=[{id:1111,amount:0.01},{id:2222,amount:0.01},{id:3333,amount:2.1}] 如何取得所有的id 并以“”分隔形式拼成字符串,同时对所有的amount求和计算

[code="java"]
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

public class Account {

private String id;
private Double amount;
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public Double getAmount() {
    return amount;
}
public void setAmount(Double amount) {
    this.amount = amount;
}

public static void main(String[] args) {

    String json = "[{id:1111,amount:0.01},{id:2222,amount:0.01},{id:3333,amount:2.1}]";
    JSONArray jsonArray = JSONArray.fromObject(json);
    List<Account> list = (List<Account>)JSONArray.toCollection(jsonArray,Account.class);
    String ids = "";
    Double amount =0.0;
    for(Account a:list){
        System.out.println(a.getId());
        System.out.println(a.getAmount());
        ids+=a.getId()+",";
        amount+=a.getAmount();
    }
    ids = ids.substring(0,ids.length()-1);
    System.out.println(ids);
    System.out.println(amount);
}

}

[/code]

json-lib-2.2.3.jar,ezmorph-1.0.2.jar下测试有效。

这个很简单,定义一个function,然后把这个数据传递进去,遍历数组,取每个对象的属性分别进行连接和计算

用Jackson,处理json的框架
[url]http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html[/url]

单纯的javascript方式

[code="js"]

var apud = [{"id":1111,"ammount":0.01},{"id":2222,"ammount":2.01},{"id":3333,"ammount":2.21}];
var ids = [];
var amount = 0;
for(var i=0;i< apud.length;i++){
ids.push(apud[i].id);
amount += +apud[i].ammount;
}
ids = ids.join(',');
console.log("ids : ",ids);
console.log("amount : ",amount);
[/code]

基于jquery解析json的方式
[code="js"]
var puduct = '[{"id":1111,"ammount":0.01},{"id":2222,"ammount":2.01},{"id":3333,"ammount":2.21}]' ;
var jsons = jQuery.parseJSON(puduct)
//console.info(jsons);
var ids = [];
var amount = 0;
$(jsons).filter(function(){
ids.push(this.id);
amount += parseFloat(this.ammount);
});
ids = ids.join(',');
console.log("ids : ",ids);
console.log("amount : ",amount);

    //下面的方式也可以,其实质还是和存js一样就是遍历数组
    var ids = [];
    var amount = 0; 
    $.each(jsons,function(idx,obj){
        ids.push(obj.id);
        amount += parseFloat(obj.ammount);
    });
    ids = ids.join(',');
    console.log("ids : ",ids);
    console.log("amount : ",amount);

[/code]

[color=red]运行结果[/color]
[quote]
ids : 1111,2222,3333
amount : 4.2299999999999995
ids : 1111,2222,3333
[color=red][b]amount : 4.2299999999999995 [/b][/color]
[/quote]

注意这里的结果!楼主可以自己在去查下介个为什么是这样!