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.
Answer from Louise on Stack Overflowdont' 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.
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.
You will need to pass a TypeReference to readValue with the desired result type:
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> data = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>(){});
Use gson with specified type to convert to list of maps:
Gson gson = new Gson();
Type resultType = new TypeToken<List<Map<String, Object>>>(){}.getType();
List<Map<String, Object>> result = gson.fromJson(json, resultType);
This fixed it for me:
JsonArray jsoncargo = jsonObject.getJsonArray("cargo");
Map<String, Integer> cargo = new HashMap<>();
for (int i = 0; i < jsoncargo.size(); i++) {
String type = jsoncargo.getJsonObject(i).getString("type");
Integer amount = jsoncargo.getJsonObject(i).getInt("amount");
cargo.put(type, amount);
}
I've been able to solve this using the Google GSON
Map<String, Integer> cargoMap = new HashMap<>();
JsonObject jsonObject = new Gson().fromJson(yourJsonString, JsonObject.class);
JsonArray cargo = jsonObject.getAsJsonArray("cargo");
cargo.forEach(item ->
{
String type = item.getAsJsonObject().get("type").getAsString();
int amount = item.getAsJsonObject().get("amount").getAsInt();
if (StringUtils.isNotBlank(type) || amount != 0) {
cargoMap.put(type, amount);
}
});
Where "yourJsonString" is the whole json that contains the cargo json array.
In recursive way:
public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
Using Jackson library:
import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, HashMap.class);
Using Gson, you can do the following:
Map<String, Object> retMap = new Gson().fromJson(
jsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
);
If you get this JSON as String then you can use ObjectMapper.readValue method
readValue(String content, TypeReference valueTypeRef)
Code
List<HashMap<String, Object>> cropDetailsList = mapper.readValue(jsonString,
new TypeReference<List<HashMap<String, Object>>>(){});
In the same way if you want to iterate JSONArray
List<HashMap<String, Object>> cropDetailsList = cropDetails.stream()
.map(eachCropJson->(HashMap<String, Object>) mapper.convertValue(eachCropJson, HashMap.class))
.collect(Collectors.toList());
Using stream this can be done
List<HashMap<String, Object>> output = cropDetails.toList().stream().map(m -> ((HashMap<String, Object>) m)).collect(Collectors.toList());
You can use Jackson ObjectMapper with TypeReference ,
First you need to read it as Map<String,Object> then you can extract the name and num with Java.
you need to get the data from obj then for each item in the dataList you have to map it to a new HashMap as shown below
ObjectMapper objectMapper = new ObjectMapper ();
Map<String,Object> jsonMap = objectMapper.readValue(jsonData,new TypeReference<Map<String,Object>>(){});
List<Object> data = ((Map<String,Object>)jsonMap.get("obj")).get("data");
List<Map<String,String> result = data.stream()
.map(d->(Map<String,Object> d)
.map(d->{
Map<String,String> map = new HashMap();
map.put(d.get("name"),((Map<String,String>)d.get("value")).get("num"));
return map;
})
.collect(Collectors.toList());
However if you can create a class for the the data it will be bit easier.
Library Josson can do the job.
https://github.com/octomix/josson
Deserialization
Josson josson = Josson.fromJsonString(
"{" +
" \"code\": 1," +
" \"msg\": \"query success\"," +
" \"obj\": {" +
" \"data\": [" +
" {" +
" \"name\": \"\"," +
" \"value\": {" +
" \"num\": \"89\"" +
" }" +
" }," +
" {" +
" \"name\": \"1\"," +
" \"value\": {" +
" \"num\": \"19\"" +
" }" +
" }," +
" {" +
" \"name\": \"2\"," +
" \"value\": {" +
" \"num\": \"6\"" +
" }" +
" }" +
" ]" +
" }," +
" \"success\": true," +
" \"duration\": 523" +
"}");
Transformation
JsonNode node = josson.getNode("obj.data.map(name::value.num)");
System.out.println(node);
List<Map<String, String>> result = Josson.readValueFor(node, List.class);
System.out.println(result);
Output
[{"":"89"},{"1":"19"},{"2":"6"}]
[{=89}, {1=19}, {2=6}]