[英]Loading MAPS into a LIST - overwriting values
下面的代碼采用一個字符串(恰好是JSON)-將其轉換為JSONObject,然后遍歷數據。 JSON具有架構(列)和數據。 我的最終目標是將每個項目鏈接起來,然后放入地圖中。
當每個項目都不同時,這非常適用,如下所示:
String jsonSTR = "{\"schema\":[\"col1\",\"col2\",\"col3\"],\"data\":[[\"banana\",\"1\",face],[\"orange\",\"2\",\"foot\"],[\"apple\",\"3\",\"hand\"]]}";
輸出量
{banana=col1, orange=col1, 1=col2, apple=col1, face=col3, 2=col2, 3=col2, foot=col3, hand=col3}
但是引入了第二個重復項(包含在下面的代碼中),我最終覆蓋了值。 我嘗試將輸入的值切換到列表中,但是存在相同的問題。
我使用了錯誤的容器來保存此數據,或者使用不正確。 我認為LISTS可能會造成重復。
這是我當前的代碼:
import org.json.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
ArrayList<String> schemaList = new ArrayList<>();
List<Map<String, Object>> allData = new ArrayList<Map<String, Object>>();
Map<String,Object> partData = new HashMap<String, Object>();
String jsonSTR = "{\"schema\":[\"col1\",\"col2\",\"col3\"],\"data\":[[\"banana\",\"orange\",2],[\"face\",\"arm\",\"eye\"],[\"yes\",\"no\",\"no\"]]}";
JSONObject jsonObj = new JSONObject(jsonSTR);
//Getting schema
JSONArray schema = jsonObj.getJSONArray("schema");
for (int i = 0; i < schema.length(); i++)
{
schemaList.add(schema.get(i).toString());
}
//Getting data
JSONArray data = jsonObj.getJSONArray("data");
for (int j = 0; j < data.length(); j++)
{
JSONArray row = data.getJSONArray(j);
for (int k = 0; k < row.length(); k++)
{
partData.put(schema.get(k).toString(),row.get(k));
allData.add(partData);
}
}
System.out.println(allData.get(0));
System.out.println(allData.get(1));
}
}
如果必須使用鍵將數據存儲在映射中,則任何列都不能重復數據,因此這不是最佳解決方案。
public static Map<String, List<String>> toMap(String jsonSTR) {
Map<String, List<String>> result = new HashMap<>();
JSONObject jsonObj = new JSONObject(jsonSTR);
JSONArray schema = jsonObj.getJSONArray("schema");
JSONArray data = jsonObj.getJSONArray("data");
for (int i = 0; i < schema.length(); i++) {
String key = schema.get(i).toString();
result.put(key, new ArrayList<>());
for (int j = 0; j < data.length(); j++)
result.get(key).add(((JSONArray)data.get(j)).get(i).toString());
}
return result;
}
在:
“ {\\” schema \\“:[\\” col1 \\“,\\” col2 \\“,\\” col3 \\“,\\” col4 \\“],\\”數據\\“:[[\\”香蕉\\“,\\” 1 \\“,\\” face \\“,\\” black \\“],[\\” orange \\“,\\” 2 \\“,\\” foot \\“,\\” red \\“],[\\” apple \\“, \\“ 3 \\”,\\“手\\”,\\“黃色\\”]]}“
出:
{col4 = [黑色,紅色,黃色],col2 = [1、2、3],col3 = [臉,腳,手],col1 = [香蕉,橙,蘋果]}
您如何看待該解決方案?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.