【问题标题】:Read JSON array into Java array/lists/map将 JSON 数组读入 Java 数组/列表/映射
【发布时间】:2015-03-29 18:00:24
【问题描述】:

所以我有这么多代码要开始(我包括导入是因为我认为您可能想查看我导入的内容):

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 谢谢。

【问题讨论】:

  • 您要读取还是写入 JSON文件?
  • 我只需要阅读它。

标签: java arrays json


【解决方案1】:

Gson 对你来说可能是一个很好的解决方案

【讨论】:

【解决方案2】:

您的 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>>

【讨论】:

    【解决方案3】:

    以下代码可能对您有所帮助

    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"));
    
        } 
    

    【讨论】:

      【解决方案4】:

      您可以将文件数据读入字符串,然后可以使用 Jackson lib 将该字符串转换为 Java Hashmap。您可以为此使用 ObjectMapper 类。 这是如何做到这一点的示例代码:

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

      在上面的代码中,jsonString 是包含 JSON 数据的字符串。 希望能解决您的问题。

      【讨论】:

        【解决方案5】:

        不知道这是否有帮助,但我使用这个来解析 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 条目的开头与给定值进行模式匹配。

        【讨论】:

          【解决方案6】:

          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);
          

          【讨论】:

            【解决方案7】:

            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 数组中的每个对象转换为映射数组中的索引。使用对象映射器将避免循环,因为下面回答的另一张海报

            【讨论】:

              猜你喜欢
              • 2017-02-24
              • 1970-01-01
              • 2021-05-18
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多