简体   繁体   中英

Read JSON array into Java array/lists/map

So I have this much code to start off (I included the import because I thought you might want to see what I imported):

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

}

The import thing is that Right now I can't write arrays in my JSON file. Basically I can't do stuff like :

{
"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"
    ]
}
}

Anyway other stuff is not important. The only thing I really need to parse is "entries", into something like String[][] or Map. Rightnow to use jsonobj.get() I must have direct entry name in my json file. Can anyone help? :D Thanks.

You can read the file data into a String and than that string can be converted into Java Hashmap by using Jackson lib. You can use ObjectMapper class for that. Here is sample code for how to do it :

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

Here in the above code jsonString is the String containing the JSON data. Hope that solves your problem.

dont' know if this will help, but I parse json using this:

 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     

into a 2d array, where the property name is the key, and the value the value (if that makes sense). then I access any given thing with

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

I have a separate routine for working out the record number, but that's just a loop with pattern matching agains a given value in the start of the Json entry.

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

Your json structure is the following :

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"]

Thus, you should take the "entries" entry (sorry for joke) with get() method and iterate over it with

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

Since the size of JSON is not defined a priori (I guess), I suggest to use a Map<String,List<String>>

The following code may help you

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

    } 

A easy solution with Genson would be to use databinding. Create a class that only declares a entries property and a class Entry containing the other properties.

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

Or deser to untyped maps/lists and extract by hand the data you want.

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 is a good library for this to convert to Json without having to create Pojos to convert the Json to an object. Assuming the array is a string input named "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);
        }

This will convert each object in the Json Array to an index in a map array. Using object mapper instead will avoid a loop as another poster answered below

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM