有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将ArrayList<String>转换为不带GSON的JSONObject

我有以下代码:

import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;

inputParams="custObj237Id,1001,custObjNm,nome1,custObjDesc,desc1,statusCd,status1,periodicity,peridiocity1,periods,period1";

String[] arrayParams = inputParams.split(",");  
List<String> listParams = new ArrayList<String>();
List<String> key        = new ArrayList<String>();
List<String> value      = new ArrayList<String>();

for(String s : arrayParams) {
    if(s != null && s.length() > 0) {
        listParams.add(s);
    }
}
        
for(int i=0;i<listParams.size;i++) {
    if (i % 2 == 0){
        key.add(listParams.get(i));
    }else{ 
        value.add(listParams.get(i));
    }
} 
     
listParams.clear();     
     
int c1 = 0, c2 = 0;
    
while(c1 < key.size() || c2 < value.size()) {
   if(c1 < key.size()){
       listParams.add((String) key.get(c1++));
   }
   if(c2 < value.size()){
       listParams.add((String) value.get(c2++));
   }
}

代码返回:

[custObj237Id, 1001, custObjNm, nome1, custObjDesc, desc1, statusCd, status1, periodicity, peridiocidade1, periods, periodo1]

如何在不使用GSON的情况下将ArrayList转换为JSONObject

[custObj237Id, 1001, custObjNm, nome1, custObjDesc, desc1, statusCd, status1, periodicity, peridiocidade1, periods, periodo1]

in 

{"custObj237Id":1001,"custObjNm":nome1,"custObjDesc":desc1,"statusCd":status1,"periodicity":periodicity1,"periods":periodo1}


共 (1) 个答案

  1. # 1 楼答案

    不使用GSON将ArrayList转换为JSONObject 你可以用

    JSONObject EdgeJsonObjsub = new JSONObject();
    JSONArray EdgeJsonArrayMain=new JSONArray();
    

    示例代码是

    public static void main(String[] args) 
        {
        List<Integer> y = new ArrayList<Integer>();
        y.add(100);
        y.add(200);
         JSONObject EdgeJsonObjsub = new JSONObject();
         JSONArray EdgeJsonArrayMain=new JSONArray();
         for(int i=0; i<y.size(); i++)
         {
             EdgeJsonArrayMain.put(y.get(i));
         }
         EdgeJsonObjsub.put("12", EdgeJsonArrayMain);
         System.out.println(EdgeJsonObjsub);
        
        }
    

    输出是

    {"12":[100,200]}