首页 > 解决方案 > 我收到一个错误,例如 JSONObject["global_collector"] is not a string,同时将 JsonObject 转换为 String 将它们保存在 Hashmap 中

问题描述

我将下面的 JsonObject 转换为字符串并将字符串值保存在 Hashmap 中。当我执行应用程序时,我收到一个错误

JSONObject["global_collector"] 不是字符串

如何解决错误?

@Service
public class CreditRiskService 
{
 public static String original1 = "";
 public static String str;
 public void getMatchingOpco() throws ParseException, FileNotFoundException, IOException
 //public Map<String, String> getMatchingOpco() throws ParseException
  {
   File file1 = new File(getClass().getClassLoader().getResource("CredirRisk_corainputtoIIB.json").getFile());
   JSONTokener jsonDataFile1 = new JSONTokener(new FileInputStream(file1));
   JSONObject jsonObject1 = new JSONObject(jsonDataFile1);
   
   //jsonObject1.optString(original1, original1)
  
   File file2 = new File(getClass().getClassLoader().getResource("opco.json").getFile());
   JSONTokener jsonDataFile2 = new JSONTokener(new FileInputStream(file2));
   JSONObject jsonObject2 = new JSONObject(jsonDataFile2);
  
   if(!JSONObject.NULL.equals(jsonObject1))
   {
    String jsonObjToString1 = (String)jsonObject1.toString();
    original1=jsonObjToString1;
    HashMap<String, String> map1 = new HashMap<>();
    Iterator<String> itr1 = jsonObject1.keys();
    while(itr1.hasNext())
    {
     String key = itr1.next();
     String value = jsonObject1.getString(key);
     System.out.println("Setting map key and value pairs");
     map1.put(key,value);
     System.out.println(key + ":" + value); 
    }
   }
  }
 } 

以下是Json:

{
    "target": "SUS",
    "source": "CORA",
    "request_tracker_id": "201013051429",
    "request_datetimestamp": "2020-10-13 05:14:29",
    "risk_code": null,
    "payment_terms": null,
    "op_code": "056",
    "global_collector": null,
    "credit_analyst": "CRDAB000",
    "account_key": "USBL056155266B"
}

标签: jsonhashmap

解决方案


推荐阅读