繁体   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