[英]Convert ArrayList<String> to JSONObject without GSON
我有以下代碼:
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}
將 ArrayList 轉換為 JSONObject 而不使用 GSON 你可以使用
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);
}
output 是
{"12":[100,200]}
我設法解決了提出的問題。 為此,我在 ArrayList 本身上創建了所需的格式,將其轉換為字符串並插入缺少的內容,以創建字符串格式的 JSONObject:
老的
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++));
}
}
新的
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++) + "\"");
}
}
String res = "";
res += "{";
res += String.join("", listParams);
res += "}";
for(int j=0;j<res.length();j++){
if(res[j] == "\"" && res[j+1] == "\""){
res = res.replaceAll("\"\"","\",\"");
}
}
返回資源:
{"custObj237Id":"1001","custObjNm":"nome1","custObjDesc":"desc1","statusCd":"status1","periodicity":"peridiocidade1","periods":"periodo1"}
此時已經有了JsonObject,但是它就像一個String,所以轉換就用下面的代碼:
JSONObject jsonObject = new JSONObject(res);
轉換為 JSONObject 后,如果搜索 a.get("key"),就會找到數據。
分辨率有點廣泛,但對於使用 GSON 有問題的人來說,它是一種替代方案。 雖然它不是“常規”的 JSON,但在某些情況下有必要這樣做。
我希望我有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.