GSON fromJSON Deserialization with Conditional to Exclude Specific Object Instances - java

Given the following JSON response:
{
"status": "OK",
"regions": [
{
"id": "69",
"name": "North Carolina Coast",
"color": "#01162c",
"hasResorts": 1
},
{
"id": "242",
"name": "North Carolina Inland",
"color": "#01162c",
"hasResorts": 0
},
{
"id": "17",
"name": "North Carolina Mountains",
"color": "#01162c",
"hasResorts": 1
},
{
"id": "126",
"name": "Outer Banks",
"color": "#01162c",
"hasResorts": 1
}
]
}
I'm trying to create a List of Region objects. Here's a very abridged version of my current code:
JSONObject jsonObject = new JSONObject(response);
String regionsString = jsonObject.getString("regions");
Type listType = new TypeToken<ArrayList<Region>>() {}.getType();
List<Region> regions = new Gson().fromJson(regionsString, listType);
This is all working fine. However, I'd like to exclude the regions in the final List that hasResorts == 0. I realize I can loop through the actual JSONObjects and check them before calling fromJSON on each region. But I'm assuming there is a GSON specific way of doing this.
I was looking at the ExclusionStrategy(). Is there a simple way to implement this to JSON deserialization?

ExclusionStrategy won't help you since it works without the context of deserialization. Indeed, you can exclude only a specific kind of class. I think that best way of doing it is through custom deserialization. Here is what I mean (you can copy&paste&try immediately):
package stackoverflow.questions.q19912055;
import java.lang.reflect.Type;
import java.util.*;
import stackoverflow.questions.q17853533.*;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
public class Q19912055 {
class Region {
String id;
String name;
String color;
Integer hasResorts;
#Override
public String toString() {
return "Region [id=" + id + ", name=" + name + ", color=" + color
+ ", hasResorts=" + hasResorts + "]";
}
}
static class RegionDeserializer implements JsonDeserializer<List<Region>> {
public List<Region> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
if (json == null)
return null;
ArrayList<Region> al = new ArrayList<Region>();
for (JsonElement e : json.getAsJsonArray()) {
boolean deserialize = e.getAsJsonObject().get("hasResorts")
.getAsInt() > 0;
if (deserialize)
al.add((Region) context.deserialize(e, Region.class));
}
return al;
}
}
/**
* #param args
*/
public static void main(String[] args) {
String json =
" [ "+
" { "+
" \"id\": \"69\", "+
" \"name\": \"North Carolina Coast\", "+
" \"color\": \"#01162c\", "+
" \"hasResorts\": 1 "+
" }, "+
" { "+
" \"id\": \"242\", "+
" \"name\": \"North Carolina Inland\", "+
" \"color\": \"#01162c\", "+
" \"hasResorts\": 0 "+
" }, "+
" { "+
" \"id\": \"17\", "+
" \"name\": \"North Carolina Mountains\", "+
" \"color\": \"#01162c\", "+
" \"hasResorts\": 1 "+
" }, "+
" { "+
" \"id\": \"126\", "+
" \"name\": \"Outer Banks\", "+
" \"color\": \"#01162c\", "+
" \"hasResorts\": 1 "+
" } "+
" ] ";
Type listType = new TypeToken<ArrayList<Region>>() {}.getType();
List<Region> allRegions = new Gson().fromJson(json, listType);
System.out.println(allRegions);
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(listType, new RegionDeserializer());
Gson gson2 = builder.create();
List<Region> regionsHaveResort = gson2.fromJson(json, listType);
System.out.println(regionsHaveResort);
}
}

Related

JSON array elements to ArrayList for JSP

I am trying to add specific values from the following JSON to a Java ArrayList. I would then like to use this ArrayList within a JSP. This is the JSON:
{
"page": 1,
"rpp": 3,
"total": 3294,
"request_time": "2018-04-23T16:10:20+01:00",
"stops": [
{
"atcocode": "370023715",
"longitude": -1.46616,
"latitude": 53.38248,
"distance": 57
},
{
"atcocode": "370027281",
"longitude": -1.46583,
"latitude": 53.38228,
"distance": 77
},
{
"atcocode": "370022803",
"longitude": -1.46616,
"latitude": 53.38227,
"distance": 80
}
]
}
I would like to add each longitude and latitude elements from under the "stops" subtree into 2 different ArrayLists. This is my attempted code for that:
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
try {
String json = readUrl (link);
JsonParser parser = new JsonParser();
JsonElement element = parser . parse (json);
if (element.isJsonObject()) {
JsonObject bus = element . getAsJsonObject ();
JsonArray array = bus . getAsJsonArray ("stops");
for (int i = 0; i < array.size(); i++) {
List<String> longitudes = new ArrayList<String>();
List<String> latitudes = new ArrayList<String>();
longitudes.add(array.get(i)).get("longitude");
latitudes.add(array.get(i)).get("latitude");
request.setAttribute("longitudes", longitudes);
request.setAttribute("latitudes", latitudes);
RequestDispatcher dispatcher = request . getRequestDispatcher ("latlong.jsp");
dispatcher.forward(request, response);
}
}
}
}
i get the following error of: "error: incompatible types: JsonElement cannot be converted to String"
Thank you in advance!
One other error you have is that the longitudes, latitudes lists are inside of the loop.
Here is a simple testable piece of code which extracts the data from the JSON and can be tested locally. You can adapt it to your purposes ...
public static void main(String[] args) {
String json = "{\n" +
"\"page\": 1,\n" +
"\"rpp\": 3,\n" +
"\"total\": 3294,\n" +
"\"request_time\": \"2018-04-23T16:10:20+01:00\",\n" +
"\"stops\": [\n" +
"{\n" +
" \"atcocode\": \"370023715\",\n" +
" \"longitude\": -1.46616,\n" +
" \"latitude\": 53.38248,\n" +
" \"distance\": 57\n" +
"},\n" +
"{\n" +
" \"atcocode\": \"370027281\", \n" +
" \"longitude\": -1.46583,\n" +
" \"latitude\": 53.38228,\n" +
" \"distance\": 77\n" +
"},\n" +
"{\n" +
" \"atcocode\": \"370022803\",\n" +
" \"longitude\": -1.46616,\n" +
" \"latitude\": 53.38227,\n" +
" \"distance\": 80\n" +
" }\n" +
"]\n" +
"}";
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
List<String> longitudes = new ArrayList<>();
List<String> latitudes = new ArrayList<>();
if (element.isJsonObject()) {
JsonObject bus = element . getAsJsonObject ();
JsonArray array = bus.getAsJsonArray("stops");
array.forEach(jsonElement -> {
extractToList(longitudes, (JsonObject) jsonElement, "longitude");
extractToList(latitudes, (JsonObject) jsonElement, "latitude");
});
}
System.out.println(longitudes);
System.out.println(latitudes);
}
private static void extractToList(List<String> list, JsonObject jsonElement, String field) {
final JsonElement longitude = jsonElement.get(field);
if(longitude != null) {
list.add(longitude.getAsString());
}
}
If you run this you get printed out on the console:
[-1.46616, -1.46583, -1.46616]
[53.38248, 53.38228, 53.38227]
I have assumed you are using Google's GSON library.
Instead of
longitudes.add(array.get(i)).get("longitude");
latitudes.add(array.get(i)).get("latitude");
Use
longitudes.add(array.get(i).get("longitude").getAsString());
latitudes.add(array.get(i).get("latitude").getAsString());

How can I structurally modify a JsonObject and replace some of its values?

I have a json in a JsonObject such as:
"customer": {
"full_name": "John John",
"personal": {
"is_active": "1",
"identifier_info": {
"hobbies": [
"skiing",
"traveling"
],
"user_id": "1234",
"office_id": "2345"
}
}
}
Is there a way to modify the JsonObject so as to remove the hobbies completely from the identifier_info and leave the rest untouched and then add the contents of hobbies the same way as the others? i.e.
"customer": {
"full_name": "John John",
"personal": {
"is_active": "1",
"identifier_info": {
"skiing":"expert",
"traveling":"rarely",
"user_id": "1234",
"office_id": "2345"
}
}
}
Find the full implementation for removing the JSON Array "hobbies" and to insert them in the parent JSON Object directly.
public class ProcessJSONString {
String data ="{\"customer\": { \n" +
" \"full_name\": \"John John\", \n" +
" \"personal\": { \n" +
" \"is_active\": \"1\", \n" +
" \"identifier_info\": { \n" +
" \"hobbies\": [ \n" +
" \"skiing\",\n" +
" \"traveling\"\n" +
" ], \n" +
" \"user_id\": \"1234\", \n" +
" \"office_id\": \"2345\"\n" +
" } \n" +
" } \n" +
"}} ";
public void processData() {
try {
JSONObject result = new JSONObject(data);
JSONObject customer = result.getJSONObject("customer");
JSONObject personal = customer.getJSONObject("personal");
JSONObject identifierInfo =
personal.getJSONObject("identifier_info");
JSONArray hobbies = identifierInfo.getJSONArray("hobbies");
identifierInfo.remove("hobbies");
//Under the assumption the tags will be added by the user, the code has been inserted.
identifierInfo.put("skiing","expert");
identifierInfo.put("traveling","rarely");
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ProcessJSONString instance = new ProcessJSONString();
instance.processData();
}
}
That should be no problem, using JsonObject's remove() method. It returns the removed JsonElement. Assuming the original json is a JsonObject called customer:
JsonObject identifierInfo = customer.getAsJsonObject("personal").getAsJsonObject("identifier_info");
JsonArray hobbies = (JsonArray) identifierInfo.remove("hobbies");
after that you can just add the hobbies to the identifierInfo and get the desired result:
for (JsonElement aHobby : hobbies) {
identifierInfo.addProperty(aHobby.getAsString(), "expert");
}
don't forget to add null checks as needed.

How to get level of each object in json where objects can have any number of children of same object type

I have an Employee level structure like below image
This structure is populated and stored with help of json like this
{
"name": "Lao Lao",
"title": "general manager",
"children": [
{
"name": "Bo Miao",
"title": "department manager",
"children": [
{
"name": "Li Jing",
"title": "senior engineer"
},
{
"name": "Li Xin",
"title": "senior engineer",
"children": [
{
"name": "To To",
"title": "engineer"
},
{
"name": "Fei Fei",
"title": "engineer"
},
{
"name": "Xuan Xuan",
"title": "engineer"
}
]
}
]
},
{
"name": "Su Miao",
"title": "department manager",
"children": [
{
"name": "Pang Pang",
"title": "senior engineer"
},
{
"name": "Hei Hei",
"title": "senior engineer",
"children": [
{
"name": "Xiang Xiang",
"title": "UE engineer"
},
{
"name": "Dan Dan",
"title": "engineer"
},
{
"name": "Zai Zai",
"title": "engineer"
}
]
}
]
}
]
}
I want to parse this Json to get all the objects with the level and parent name like this
{name = Lao lao , parent = null , level = 1 }
{name = Bao Miao , parent = Lao lao , level = 2 }
..................................................
{name = Li Jing , parent = Bao Miao , level = 3 }
How can we parse this with help of java?If there is any library with such functionality, please let me know.
Implement Model definition as below. Also put level and parentName in Model class.
class Employee{
String name;
String title;
Employee children[];
int level;
String parentName;
#Override
public String toString(){
return "{name = "+name+" , parent = "+parentName+ ", level = "+level+ " }";
}
}
Parse the json data using GSON API.
Employee e= new Gson().fromJson(new JsonReader(new FileReader("file.json")), Employee.class);
This is complete program for you. Finally i was able to write all the code for you after spending an hour on this. Working fine so far :)
import java.io.FileReader;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
public class ParseJson {
public static void main(String a[]) {
Gson g = new Gson();
try {
Employee e = g.fromJson(new JsonReader(new FileReader("file.json")), Employee.class);
parseEmployees(e);
printEmployee(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
private static void parseEmployees(Employee e) {
setParentAndLevel(e, 1, null);
}
private static void setParentAndLevel(Employee e, int lvl, String parent) {
e.level = lvl;
e.parentName = parent;
if (e.children != null && e.children.length > 0) {
lvl++;
for (Employee emp : e.children) {
setParentAndLevel(emp, lvl, e.name);
}
}
}
public static void printEmployee(Employee e){
System.out.println(e);
if (e.children != null && e.children.length > 0) {
for (Employee emp : e.children) {
printEmployee(emp);
}
}else{
return ;
}
}
}
class Employee {
String name;
String title;
Employee children[];
int level;
String parentName;
#Override
public String toString() {
return "{name = " + name + " , parent = " + parentName + ", level = " + level + " }";
}
}
Output :
{name = Lao Lao , parent = null, level = 1 }
{name = Bo Miao , parent = Lao Lao, level = 2 }
{name = Li Jing , parent = Bo Miao, level = 3 }
{name = Li Xin , parent = Bo Miao, level = 3 }
{name = To To , parent = Li Xin, level = 4 }
{name = Fei Fei , parent = Li Xin, level = 4 }
{name = Xuan Xuan , parent = Li Xin, level = 4 }
{name = Su Miao , parent = Lao Lao, level = 2 }
{name = Pang Pang , parent = Su Miao, level = 3 }
{name = Hei Hei , parent = Su Miao, level = 3 }
{name = Xiang Xiang , parent = Hei Hei, level = 4 }
{name = Dan Dan , parent = Hei Hei, level = 4 }
{name = Zai Zai , parent = Hei Hei, level = 4 }
look like I have so much time and waste my time doing this for you because it sound challenging basically I turn this into a jsonObject first then I do a bfs graph walk to find the level and parent told you it is a graph problem again there is some bug on the level but I want the community or you to fix the bug yourself
EDIT: I have fix the level bug for you already again ask me if you have any question
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception{
String JSON_STRING = "{\n" +
" \"name\": \"Lao Lao\",\n" +
" \"title\": \"general manager\",\n" +
" \"children\": [\n" +
" {\n" +
" \"name\": \"Bao Miao\",\n" +
" \"title\": \"department manager\",\n" +
" \"children\": [\n" +
" {\n" +
" \"name\": \"Li Jing\",\n" +
" \"title\": \"senior engineer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"Li Xin\",\n" +
" \"title\": \"senior engineer\",\n" +
" \"children\": [\n" +
" {\n" +
" \"name\": \"To To\",\n" +
" \"title\": \"engineer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"Fei Fei\",\n" +
" \"title\": \"engineer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"Xuan Xuan\",\n" +
" \"title\": \"engineer\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"name\": \"Su Miao\",\n" +
" \"title\": \"department manager\",\n" +
" \"children\": [\n" +
" {\n" +
" \"name\": \"Pang Pang\",\n" +
" \"title\": \"senior engineer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"Hei Hei\",\n" +
" \"title\": \"senior engineer\",\n" +
" \"children\": [\n" +
" {\n" +
" \"name\": \"Xiang Xiang\",\n" +
" \"title\": \"UE engineer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"Dan Dan\",\n" +
" \"title\": \"engineer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"Zai Zai\",\n" +
" \"title\": \"engineer\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}] \n";
JSONObject obj = new JSONObject(JSON_STRING);
Deque<JSONObject> deque = new ArrayDeque<>();
Map<String, String> res = new HashMap<>();
int level = 1;
res.put("NULL", obj.getString("name")+ "-" + level);
deque.add(obj);
Map<String, Integer> levelmap = new HashMap<>();
levelmap.put(obj.getString("name"), 1);
while (!deque.isEmpty()){
JSONObject u = deque.poll();
try {
JSONArray children = u.getJSONArray("children");
for (int i = 0; i < children.length(); i++) {
deque.add(children.getJSONObject(i));
levelmap.put(children.getJSONObject(i).getString("name"), levelmap.get(u.getString("name")) + 1);
res.put(children.getJSONObject(i).getString("name"), u.getString("name") + "-" + levelmap.get(children.getJSONObject(i).getString("name")));
}
}catch (JSONException jex){
System.out.println("end of the tree");
}
}
//turn it back into a json array format
String str = new String("[]");
JSONArray jsonArray = new JSONArray(str);
System.out.println(res);
for(String key: res.keySet()){
String st = new String("{}");
JSONObject jsonObject = new JSONObject(st);
//key is parent
String[] tok = res.get(key).split("-");
String child = tok[0];
String mylevel = tok[1];
jsonObject.put("name", key);
jsonObject.put("level", mylevel);
jsonObject.put("parent", child);
jsonArray.put(jsonObject);
}
System.out.println(jsonArray.toString(2));
}
}
output:
[
{
"parent": "Hei Hei",
"level": "4",
"name": "Xiang Xiang"
},
{
"parent": "Lao Lao",
"level": "2",
"name": "Bao Miao"
},
{
"parent": "Lao Lao",
"level": "1",
"name": "NULL"
},
{
"parent": "Su Miao",
"level": "3",
"name": "Hei Hei"
},
{
"parent": "Hei Hei",
"level": "4",
"name": "Dan Dan"
},
{
"parent": "Hei Hei",
"level": "4",
"name": "Zai Zai"
},
{
"parent": "Li Xin",
"level": "4",
"name": "Xuan Xuan"
},
{
"parent": "Su Miao",
"level": "3",
"name": "Pang Pang"
},
{
"parent": "Li Xin",
"level": "4",
"name": "Fei Fei"
},
{
"parent": "Li Xin",
"level": "4",
"name": "To To"
},
{
"parent": "Bao Miao",
"level": "3",
"name": "Li Jing"
},
{
"parent": "Lao Lao",
"level": "2",
"name": "Su Miao"
},
{
"parent": "Bao Miao",
"level": "3",
"name": "Li Xin"
}
]
Yes, you can do this. First, you need to map this json to POJO.
So, Create a model class like this
class Employee{
String name;
String title;
List<Employee> Children;
}
If you can map this json to POJO. Then you only need to run through a loop to get what you want.

Convert JSON Object as a Flat Obejct with Key value pair

I am getting a JSON object which looks like:
{
"id": "1",
"name": "Hw",
"price": {
"value": "10"
},
{
"items": [{
"id": "1"
}]
}
}
I want to represent this as flat map, but I want to represent the array of items as a list.
My output should look like:
{
"id": "1",
"name":"Hw",
"price":"10",
"items": ["1"]
}
Can anybody suggest me how I can achieve this? I tried this approach:
How to deserialize JSON into flat, Map-like structure?
Output from the above tried link:
{
"id": "1",
"name":"Hw",
"price.value":"10",
"items[0].id": "1"
}
But it is representing the arrays values as array[0], array[1] which I don't need. I need this array as a list.
The JSON you've given is not valid. I assume it's:
{
"id": "1",
"name": "Hw",
"price": {
"value": "10"
},
"items": [{
"id": "1"
}]
}
There cannot be a generic solution to what you're asking. But for this particular JSON, this will do(using json-simple):
#SuppressWarnings("unchecked")
public Map<String, String> transform(String inputJSON) throws ParseException {
Map<String, String> result = new LinkedHashMap<>();
JSONObject inputJSONObj = (JSONObject) new JSONParser().parse(inputJSON);
String id = inputJSONObj.getOrDefault("id", "").toString();
String name = inputJSONObj.getOrDefault("name", "").toString();
String price = ((JSONObject) inputJSONObj.getOrDefault("price", new JSONObject())).getOrDefault("value", "")
.toString();
JSONArray itemsArray = (JSONArray) inputJSONObj.getOrDefault("items", new JSONArray());
int n = itemsArray.size();
String[] itemIDs = new String[n];
for (int i = 0; i < n; i++) {
JSONObject itemObj = (JSONObject) itemsArray.get(i);
String itemId = itemObj.getOrDefault("id", "").toString();
itemIDs[i] = itemId;
}
result.put("id", id);
result.put("name", name);
result.put("price", price);
result.put("items", Arrays.toString(itemIDs));
return result;
}
An approach for you with Gson. This do exactly what you want " represent this as flat map, but I want to represent the array of items as a list"
public class ParseJson1 {
public static void main (String[] args){
Type type = new TypeToken<HashMap<String, Object>>() {
}.getType();
Gson gson = new Gson();
String json = "{\n" +
" \"id\": \"1\",\n" +
" \"name\": \"Hw\", \n" +
" \"price\": {\n" +
" \"value\": \"10\"\n" +
" },\n" +
" \"items\": [{\n" +
" \"id\": \"1\"\n" +
" }]\n" +
" }\n";
HashMap<String, Object> map = gson.fromJson(json, type);
Object val = null;
for(String key : map.keySet()){
val = map.get(key);
if(val instanceof List){
for(Object s : (List)val){
System.out.println(key + ":" + s);
}
} else
System.out.println(key + ":" + map.get(key));
}
}
}
you have to convert your String in Map collection Map<String, String> which will help you to convert your Map Array to JSON format.
JSONObject jsonObject = new JSONObject();
Map<String, String> mapObject = new HashMap<String, String>();
mapObject.put("id", "1");
mapObject.put("name", "VBage");
mapObject.put("mobile", "654321");
jsonObject.put("myJSON", mapObject);
System.out.println(jsonObject.toString());
First, the JSON does not seems to have a correct format. Do you mean this?
{
"id": "1",
"name": "Hw",
"price": {
"value": "10"
},
"items": [{
"id": "1"
}]
}
In addition, since you were attaching the link of (How to deserialize JSON into flat, Map-like structure?), I assume you wants to flatten the JSON in the same manner, in which the result should be
{
id=1,
name=Hw,
price.value=10,
items[0]=1,
}
Also, if you just want the item to return a list of id (i.e. "items": ["1"]), then it is more logical to get a JSON of
{
"id": "1",
"name": "Hw",
"price": {
"value": "10"
},
"items": [ "1" ] // instead of "items": [{"id": "1"}]
}
The link that you have attached (How to deserialize JSON into flat, Map-like structure?) provides a general solution without any customization. It shouldn't know that "id" is the value you want to append on items.
Therefore, my first suggestion is to change the JSON to be "items": [ "1" ]
If for any reasons the JSON cannot be changed, then you will need to do some customization, which will be like this:
import org.codehaus.jackson.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
import org.codehaus.jackson.node.ValueNode;
import org.junit.Test;
public class Main {
String json = "{\n" +
" \"id\": \"1\",\n" +
" \"name\": \"Hw\", \n" +
" \"price\": {\n" +
" \"value\": \"10\"\n" +
" },\n" +
" \"items\": [{\n" +
" \"id\": \"1\"\n" +
" }]\n" +
" }\n";
#Test
public void testCreatingKeyValues() {
Map<String, String> map = new HashMap<String, String>();
try {
addKeys("", new ObjectMapper().readTree(json), map);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(map);
}
private void addKeys(String currentPath, JsonNode jsonNode, Map<String, String> map) {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Map.Entry<String, JsonNode>> iter = objectNode.getFields();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
// Customization here
if (entry.getKey().equals("items")) {
ArrayNode arrayNode = (ArrayNode) entry.getValue();
for (int i = 0; i < arrayNode.size(); i++) {
addKeys(currentPath + entry.getKey() + "[" + i + "]", arrayNode.get(i).get("id"), map);
}
} else {
addKeys(pathPrefix + entry.getKey(), entry.getValue(), map);
}
}
} else if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
for (int i = 0; i < arrayNode.size(); i++) {
addKeys(currentPath + "[" + i + "]", arrayNode.get(i), map);
}
} else if (jsonNode.isValueNode()) {
ValueNode valueNode = (ValueNode) jsonNode;
map.put(currentPath, valueNode.asText());
}
}
}
Try understanding the format that you need, and then study the above code. It should give you the answer.

How to read Json with Gson

HOw would I go about parsing JSON using the google GSON library? An example of my returned JSON is:
[
{
"title": "Down",
"album": "Down",
"length": 212.61,
"artist": "Jay Sean"
},
{
"title": "Come to Me (Peace)",
"album": "Growing Pains",
"length": 301.844,
"artist": "Mary J Blige"
}
]
This is an array of json objects, is that right? How would I go about extracting this with Gson? This is what im trying but am getting null pointer exceptions:
JsonElement jelement = new JsonParser().parse(jsonInfo);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("");
JsonArray jarray = jobject.getAsJsonArray("");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("title").toString();
You must create a Type instance for List.
class MyObj {
String title;
String album;
double length;
String artist;
}
String json = "[\n" +
" {\n" +
" \"title\": \"Down\",\n" +
" \"album\": \"Down\",\n" +
" \"length\": 212.61,\n" +
" \"artist\": \"Jay Sean\"\n" +
" },\n" +
" {\n" +
" \"title\": \"Come to Me (Peace)\",\n" +
" \"album\": \"Growing Pains\",\n" +
" \"length\": 301.844,\n" +
" \"artist\": \"Mary J Blige\"\n" +
" }\n" +
"]";
Type listType = new TypeToken<List<MyObj>>() {}.getType();
List<MyObj> list = new Gson().fromJson(json, listType);
System.out.println(new Gson().toJson(list));
Gson gson = new Gson();
gson. //a lot methods

Categories

Resources