簡體   English   中英

將 JSON 數組讀入 Java 數組/列表/映射

[英]Read JSON array into Java array/lists/map

所以我有這么多代碼要開始(我包含了導入,因為我認為你可能想看看我導入的內容):

import java.sql.Array;
import java.util.Map;

import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import dataProcessing.Config.Config;

import java.io.*;

public class Reader {
private String file_path;
private FileReader fReader;

public Reader(String filePath) {
    this.file_path = filePath;
    try {
        fReader = new FileReader(file_path);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public Config read() {
    Config c = new Config();
    JSONParser parser = new JSONParser();
    Object obj = null;
    try {
        obj = parser.parse(fReader);
    } catch (Exception e){
        //ignore this
    }
    JSONObject jsonobj = (JSONObject) obj;
    if (jsonobj != null) {
        c.dailyWorkTime = (Long) jsonobj.get("dailyWorkTime");
        c.dburl = (String) jsonobj.get("db_url");
        c.username = (String) jsonobj.get("username");
        c.password = (String) jsonobj.get("password");
        c.millis = (Long) jsonobj.get("millis");
    }
    return c;
}

}

重要的是,現在我無法在我的 JSON 文件中寫入數組。 基本上我不能做這樣的事情:

{
"database_info": {
    "db_url": "hi",
    "username": "root",
    "password": "root"
},
"system_configuration": {
    "dailyWorkTime": 22,
    "millis": 600000
},
"entries": {
    "organization": [
        "orgid","orgname","orgprojects"
    ],
    "store" : [
        "stid","stname","st_belong_org"
    ],
    "customers" :[
        "phonenumber","facebookid","twitterid","instagramid"
    ]
}
}

反正其他東西不重要。 我唯一真正需要解析的是“條目”,比如 String[][] 或 Map。 現在要使用 jsonobj.get() 我必須在我的 json 文件中有直接的條目名稱。 任何人都可以幫忙嗎? :D 謝謝。

您可以將文件數據讀入字符串,然后可以使用 Jackson lib 將該字符串轉換為 Java Hashmap。 您可以為此使用 ObjectMapper 類。 這是有關如何執行此操作的示例代碼:

ObjectMapper objectMapper = new ObjectMapper();
HashMap<String, String> tempMap = objectMapper.readValue(jsonString,
            new TypeReference<HashMap<String, String>>() {
            });

在上面的代碼中,jsonString 是包含 JSON 數據的字符串。 希望能解決您的問題。

不知道這是否有幫助,但我使用這個解析 json:

 List<Map<String, String>> DataStruct = new ArrayList<Map<String, String>>();

JSONObject jSONObject = new JSONObject(Result);             
                    JSONArray entriesArr = jSONObject.getJSONArray("entries");
                    ItemsThisPage = entriesArr.length();
                      for (int i=0; i<ItemsThisPage; i++)
                      {
                          // FOR EACH ENTRY
                          JSONObject OneEntry = entriesArr.getJSONObject(i);
                          int OneEntrySize = OneEntry.length();
                          JSONArray EntKey = OneEntry.names(); 
                           Map<String, String> JsonItem = new HashMap<String, String>();
                          for (int j=0; j<OneEntrySize;j++)
                          {   // FOR EACH ITEM IN AN ENTRY
                              EntVal = EntKey.getString(j);
                              GenCell = OneEntry.opt(EntVal).toString();
                              JsonItem.put(EntVal, GenCell);            
                          }                       
                          DataStruct.add(JsonItem);                 
                      }    // end page loop     

進入一個二維數組,其中屬性名稱是鍵,值是值(如果有意義的話)。 然后我訪問任何給定的東西

Itemname = DataStruct.get(Record_Number).get("Json Key here");

我有一個單獨的例程來計算記錄號,但這只是一個循環,模式匹配再次與 Json 條目開頭的給定值。

Gson對你來說可能是一個很好的解決方案

您的 json 結構如下:

json ---> ["database_info","system_configuration","entries"]

    database_info ---> ["db_url": "hi","username": "root","password": "root"]

    system_configuration ---> [ "dailyWorkTime": 22, "millis": 600000]

    entries ---> ["organization", "store", "customers"]

         organization ---> ["orgid","orgname","orgprojects"]

         store ---> ["stid","stname","st_belong_org"]

         customers ---> ["phonenumber","facebookid","twitterid","instagramid"]

因此,您應該使用 get() 方法獲取“條目”條目(抱歉開玩笑)並使用

for(...)
  for(...)

由於 JSON 的大小不是先驗定義的(我猜),我建議使用Map<String,List<String>>

以下代碼可能對您有所幫助

FileReader reader = new FileReader(filePath);// the file which has json data
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

// get an array from the JSON object

JSONArray lang= (JSONArray) jsonObject.get("key");

// take the elements of the json array

    for(int i=0; i<lang.size(); i++){

        System.out.println("The " + i + " element of the array: "+lang.get(i));

    }

    Iterator i = lang.iterator();



    // take each value from the json array separately

    while (i.hasNext()) {

        JSONObject innerObj = (JSONObject) i.next();

        System.out.println(innerObj.get("key1") +

                 + innerObj.get("key2"));

    } 

Genson 的一個簡單解決方案是使用數據綁定。 創建一個僅聲明條目屬性的類和包含其他屬性的類條目。

class Wrapper {
  public Entry entries;
}

class Entry {
  List<String> organization, store, customers;
}

Genson genson = new Genson();
Wrapper w = genson.deserialize(new FileReader(file_path), Wrapper.class);

或者選擇無類型的地圖/列表並手動提取您想要的數據。

Map<String, Object> json = genson.deserialize(new FileReader(file_path), Map.class);
Map<String, List<String>> entries = ((Map<String, List<String>>) json.get("entries"));
// from here you have direct access to organization, store and customers
List<String> organization = entries.get(organization);

Gson 是一個很好的庫,可以將其轉換為 Json,而無需創建 Pojos 將 Json 轉換為對象。 假設數組是一個名為“json”的字符串輸入:

        JsonArray array = gson.fromJson(json, JsonArray.class);
        Map[] maps = new Map[array.size()];
        for (int i = 0; i < array.size(); i++) {
            maps[i] = gson.fromJson(array.get(i), Map.class);
        }

這會將 Json 數組中的每個對象轉換為地圖數組中的索引。 使用對象映射器將避免循環,因為下面的另一張海報已回答

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM