jsonobject值转换为另一个具有键值对的jsonobject

anauzrmj  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(397)

我有这样一个json

{

      "result":
 {

    "issue_date": "xx-yy-zzzz",
    "father/husband": "TEST",
    "name": "ABC ",
    "blood_group": "",
    "dob": "xx-yy-zzzz",
    "validity": {
      "non-transport": "xx-yy-zzzz to xx-yy-zzzz",
      "transport": "xx-yy-zzzz to xx-yy-zzzz"
    },
    "cov_details": {
      "MCWG": "NA",
      "3WTR": "NA",
      "PSV BUS": "NA",
      "LMV": "NA",
      "INVCRG": "NA"
    },
    "address": "ABC"
  }
}
JSONObject dlData = new JSONObject();
     JSONObject dlObj = new JSONObject();
     JSONObject dlcov = new JSONObject();
     JSONObject dlCovs = new JSONObject();
    dlCov = jsonObject.getJSONObject("result").getJSONObject("cov_details");

为了访问cov\u details的数据,我使用这个代码块来存储cov\u details对象中的细节

dlcov = jsonObject.getJSONObject("result").getJSONObject("cov_details");
        Iterator<String> x = dlcov.keys();
            while (x.hasNext()){
                String key1 = x.next();
                String value1 = dlcov.optString(key1);
                dlCovs.put("covabbrv",key1);
                dlCovs.put("dcIssuedt",value1);
                dlCovs.put("vecatg",key1);

            }

        dlData.put("dlCovs", dlCovs);

我正在尝试在dlcovs中存储每个值,但它只存储对象中的最后一个值,我可以使用它们存储dlcovs objet中的所有值及其键值并对其进行迭代。任何帮助都将是非常值得赞赏的,提前感谢。在此处输入代码

wbrvyc0a

wbrvyc0a1#

使用 JSONArray 对于covabrv、dcissuedt和vecatg

JSONArray covabbrv = new JSONArray();
JSONArray dcIssuedt = new JSONArray();
JSONArray vecatg = new JSONArray();
Iterator<String> x = dlcov.keys();
    while (x.hasNext()){
        String key1 = x.next();
        String value1 = dlcov.optString(key1);
        covabbrv.put(key1);
        dcIssuedt.put(value1);
        vecatg.put(key1);
    }
dlCovs.put("covabbrv",covabbrv);
dlCovs.put("dcIssuedt",dcIssuedt);
dlCovs.put("vecatg",vecatg);

输出如下:

{
    "covabbrv" : ["MCWG", "3WTR", "PSV BUS", "LMV", "INVCRG"],
    "dcIssuedt" : ["NA", "NA", "NA", "NA", "NA"],
    "vecatg" : ["MCWG", "3WTR", "PSV BUS", "LMV", "INVCRG"]
}
xn1cxnb4

xn1cxnb42#

dlCovs 作为一个jsonarray,我会这样做:

JSONArray dlCovs = new JSONArray();
dlcov = jsonObject.getJSONObject("result").getJSONObject("cov_details");
Iterator<String> x = dlcov.keys();
while (x.hasNext()) {
    String key1 = x.next();
    String value1 = dlcov.optString(key1);

    JSONObject currentDlCov = new JSONObject();
    currentDlCov.put("covabbrv",key1);
    currentDlCov.put("dcIssuedt",value1);
    currentDlCov.put("vecatg",key1);

    dlCovs.add(currentDlCov);
}

dlData.put("dlCovs", dlCovs);

这将添加一个jsonobjects数组作为 dlCovs 如果你的 dlData jsonobject。

相关问题