2017-04-07 48 views
0

我有以下对象:获取JSONArray和写入JSONArray

{ 
    "some_prop": "sweetvalue", 
    "some_list": ["0f9f822cd7e64000ac056ebc17b82f1d", "0f9f82223094fj7b82f1d"] 
} 

而我试图让some_list和写入some_list,之后保存到一个文件中。使用下面的代码:

public String getData(String key) { // this is confusion should be getConfigValue 
    String data = getConfig(); 
    JSONObject jsonData; 
    Object content = null; 
    try { 
     jsonData = new JSONObject(data); 
     if (key != null) { 
      content = jsonData.getString(key); 
     } else { 
      content = jsonData.toString(); 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return content.toString(); 
} 

private void saveFile(String data) { 
    File file = configFile; 
    try (FileOutputStream fop = new FileOutputStream(file)) { 
     if (!file.exists()) file.createNewFile(); 
     byte[] contentInBytes = data.getBytes(); 
     fop.write(contentInBytes); 
     fop.flush(); 
     fop.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

public void appendToArrayValue(String uuid) { 
    JSONObject configData = new JSONObject(getConfig()); 
    JSONArray mutedPlayers = configData.getJSONArray("some_list"); 
    JSONArray uuidArray = new JSONArray(uuid); 

    JSONArray newArray = concatArray(mutedPlayers, uuidArray); 

    JSONObject newConfigData = configData.put("some_list", newArray); 
    saveFile(newConfigData.toString()); 
} 

当尝试运行这段代码,我得到以下错误:

org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]

我不知道什么是真的错了,我知道我的代码是可怕但就是这样。

回答

0

看起来像错误是在线JSONArray uuidArray = new JSONArray(uuid);

因为prevoius行JSONArray mutedPlayers = configData.getJSONArray("some_list");应该正常工作。 如果是这样,你传递的不是数组new JSONArray(uuid),因为uuid是你的整个JSON对象。