1

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.

asked Jan 30, 2015 at 9:31
2
  • Do you want to read from or write to a JSON file? Commented Jan 30, 2015 at 9:36
  • I only need to read form it. Commented Jan 30, 2015 at 9:46

7 Answers 7

2

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.

Ram Ghadiyaram
29.4k16 gold badges102 silver badges134 bronze badges
answered Jan 30, 2015 at 10:08
Sign up to request clarification or add additional context in comments.

Comments

2

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.

answered Jan 30, 2015 at 10:07

Comments

1

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

answered Jan 7, 2021 at 13:53

Comments

0

Gson could be a good solution for you

answered Jan 30, 2015 at 9:38

2 Comments

Actually I have tried a lot of different libraries. If Gson works I can take a look at that. Thanks in advanced!
@BensonZang take a look at stackoverflow.com/questions/22271779/…
0

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

answered Jan 30, 2015 at 9:51

Comments

0

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"));
 } 
answered Jan 30, 2015 at 9:58

Comments

0

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);
answered Jan 30, 2015 at 11:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.