修改JSONArray里所有key的值

时间:2022-02-25 19:17:46

下面举一个代码的列子目的是实现如下功能:

[{"userId":1,"userName":"plf"},{"userId":2,"userName":"phy"},{"userId":3,"userName":"ply"}]

变成

[{"user_id":1,"user_name":"plf"},{"user_id":2,"user_name":"phy"},{"user_id":3,"user_name":"ply"}]

我们可以通过如下的代码实现:

public JSONArray getNewJSONArray(JSONArray array){
         JSONArray a1=new JSONArray();
         JSONObject aa=new JSONObject();
         for(int i=0;i<array.size();i++){
             JSONObject a= (JSONObject)array.get(i);
             Iterator itt = a.keys();
             Set set=a.keySet();
             List list=new ArrayList(set);
             for(int j=0;j<list.size();j++){
                 aa.put(isAcronym(list.get(j)+""), a.opt(list.get(j)+""));
             }
             a1.add(aa);
            
         }
        return a1;
    }
  //利用函数将userId-->>user_id
public String isAcronym(String word) { StringBuffer words = new StringBuffer(); for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (!Character.isLowerCase(c)&&i!=0) { String w=c+""; w="_"+w.toLowerCase(); words.append(w); }else{ words.append(c); } } return words.toString(); }