I have the following json:
[
{
"": "",
"substituted_restday": "2020-02-01",
"original_restday": "2020-02-08",
"id": "15d13f70-c0a852c0-3a925f13-6dca1982",
"_UNIQUEKEY_": "15d1592a-c0a852c0-3a925f13b7c65023",
"parentId": ""
},
{
"": "",
"substituted_restday": "2020-02-03",
"original_restday": "2020-02-09",
"id": "15d14d55-c0a852c0-3a925f13-727b70af",
"_UNIQUEKEY_": "15d1592a-c0a852c0-3a925f13-3711a584",
"parentId": ""
}
]
I want to get the value of "substituted_restday" and "original_restday" from the JSON. So I used gson.from with the following syntax to concert it into JAVA object.
String[] str = gson.fromJson(JSON, String[].class);
However, it showed the following error:
com.google.gson.JsonParseException: The JsonDeserializer StringTypeAdapter failed to deserialize json object {"":"","substituted_restday":"2020-02-01","original_restday":"2020-02-08","id":"15d13f70-c0a852c0-3a925f13-6dca1982","_UNIQUEKEY_":"15d1592a-c0a852c0-3a925f13-b7c65023","parentId":""} given the type class java.lang.String
So, how can I get the value of "substituted_restday" and "original_restday" from the JSON? Thank you?
Tree Structure
Gson can parse the JSON into a tree structure, similar to how XML can be parsed into a DOM tree. The nodes of the tree can be one of these subclasses of JsonElement: JsonObject, JsonArray, JsonPrimitive, and JsonNull.
Since the JSON starts with a [, you can parse into a JsonArray, like this:
JsonArray root = gson.fromJson(JSON, JsonArray.class);
for (JsonElement elem : root) {
JsonObject obj = elem.getAsJsonObject();
String substituted_restday = obj.get("substituted_restday").getAsString();
String original_restday = obj.get("original_restday").getAsString();
System.out.printf("substituted_restday = '%s', original_restday = '%s'%n",
substituted_restday, original_restday);
}
List of Maps
Gson can parse the JSON objects into a Map.
List<Map<String, String>> root = gson.fromJson(JSON, new TypeToken<List<Map<String, String>>>() {}.getType());
for (Map<String, String> obj : root) {
String substituted_restday = obj.get("substituted_restday");
String original_restday = obj.get("original_restday");
System.out.printf("substituted_restday = '%s', original_restday = '%s'%n",
substituted_restday, original_restday);
}
Array of POJOs
Gson can parse the JSON objects into POJOs. This is the most type-safe way to handle the data.
MyObj[] root = gson.fromJson(JSON, MyObj[].class);
for (MyObj obj : root) {
System.out.printf("substituted_restday = '%s', original_restday = '%s'%n",
obj.substitutedRestday, obj.originalRestday);
}
class MyObj {
#SerializedName("")
String blank;
#SerializedName("substituted_restday")
String substitutedRestday;
#SerializedName("original_restday")
String originalRestday;
#SerializedName("id")
String id;
#SerializedName("_UNIQUEKEY_")
String uniqueKey;
#SerializedName("parentId")
String parentId;
}
You would likely want getter and setter methods on your POJO. This is just a simplified running example.
Output (from all 3)
substituted_restday = '2020-02-01', original_restday = '2020-02-08'
substituted_restday = '2020-02-03', original_restday = '2020-02-09'
JsonObject jsonObject = gson.fromJson( JSON, JsonObject.class);
then
jsonObject.get(substituted_restday); // returns a JsonElement for that name
jsonObject.get(original_restday);
Imo, you should create a pojo for the json element and then have fromJson method return an array of that pojo's. This link should give you more details - https://howtodoinjava.com/gson/gson-parse-json-array/
Related
I have a huge JSON but I only need to parse specific fields. I know paths to these fields so I decided to try JPath and it works but I want to parse all fields at once.
Let's say I have such JSON:
{
"data": [
{
"field1": 1,
"field2": 1,
...
"another_data": [ {
"required_field1": "1",
"required_field2": "2"
}
],
...
}
]
}
I want to get only required fields with these paths and map it to Java POJO:
$.data[*].another_data[*].required_field1
$.data[*].another_data[*].required_field2
So as a final result I want to have a list of Java objects, where the object contains required_field1 and required_field2.
UPD:
how it works now
I have a Java POJO that's a container
class RequiredInfo {
private String field1;
private String field2;
//constructor, setters, etc
}
I read JSON path 2 times by using JPath:
String json = "...";
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
List<String> reqFields1 = JsonPath.read(document, "$.data[*].another_data[*].required_field1");
List<String> reqFields2 = JsonPath.read(document, "$.data[*].another_data[*].required_field2")
and then I map it to my POJO
for (int i = 0; i < reqFields1.size(); i++) {
res.add(new RequiredInfo(reqFields1.get(i), reqFields2.get(i)));
}
bit I think there is a better way how I can do it
You can try by creating a JSON object and get data:
JSONObject yourJsonObject = (JSONObject) new JSONParser().parse(yourJson);
JSONObject data = (JSONObject) yourJsonObject.get("data");
JSONObject data0 = (JSONObject) data.get(0);
JSONObject another_data = (JSONObject) data0.get("another_data");
String required_field1 = another_data.get("required_field1").toString();
String required_field2 = another_data.get("required_field2").toString();
Now that you have values, you can add them in your POJOs.
I have a JSON array of the form:
[
[
1232324343,
"A",
"B",
3333,
"E"
],
[
12345424343,
"N",
"M",
3133,
"R"
]
]
I want to map each element of the parent array to a POJO using the Jackson library. I tried this:
ABC abc = new ABC();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(data).get("results");
if (jsonNode.isArray()) {
for (JsonNode node : jsonNode) {
String nodeContent = mapper.writeValueAsString(node);
abc = mapper.readValue(nodeContent,ABC.class);
System.out.println("Data: " + abc.getA());
}
}
where ABC is my POJO class and abc is the object but I get the following exception:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.demo.json.model.ABC
EDIT:
My POJO looks like this:
class ABC{
long time;
String a;
String b;
int status;
String c;
}
Can someone suggest a solution for this?
EDIT 2: After consulting a lot of answers on StackOverflow and other forums, I came across one solution. I mapped the returned value of readValue() method into an array of POJO objects.
ABC[] abc = mapper.readValue(nodeContent, ABC[].class);
But now I am getting a separate exception
Can not construct instance of ABC: no long/Long-argument constructor/factory method to deserialize from Number value (1552572583232)
I have tried the following but nothing worked:
1. Forcing Jackson to use ints for long values using
mapper.configure(DeserializationFeature.USE_LONG_FOR_INTS, true);
2. Using wrapper class Long instead of long in the POJO
Can anyone help me with this?
You can use ARRAY shape for this object. You can do that using JsonFormat annotation:
#JsonFormat(shape = Shape.ARRAY)
class ABC {
And deserialise it:
ABC[] abcs = mapper.readValue(json, ABC[].class);
EDIT after changes in question.
You example code could look like this:
JsonNode jsonNode = mapper.readTree(json);
if (jsonNode.isArray()) {
for (JsonNode node : jsonNode) {
String nodeContent = mapper.writeValueAsString(node);
ABC abc = mapper.readValue(nodeContent, ABC.class);
System.out.println("Data: " + abc.getA());
}
}
We can use convertValue method and skip serializing process:
JsonNode jsonNode = mapper.readTree(json);
if (jsonNode.isArray()) {
for (JsonNode node : jsonNode) {
ABC abc = mapper.convertValue(node, ABC.class);
System.out.println("Data: " + abc.getA());
}
}
Or even:
JsonNode jsonNode = mapper.readTree(json);
ABC[] abc = mapper.convertValue(jsonNode, ABC[].class);
System.out.println(Arrays.toString(abc));
Your json does not map to the pojo that you have defined. For the pojo that you have defined, the json should be of the form below.
{
"time:1232324343,
"a":"A",
"b":"B",
"status":3333,
"c":"E"
}
"biodata": {
"Ruby": {
"Expertise": "web development",
"EXperience": "5 years"
},
"Dylon": {
"Expertise": "Java",
"EXperience": "2 years"
}
}
I have the above JSONObject . I am trying to fetch some keys here .
I am looking to fetch the name key i.e Ruby , Dylon etc .
I am then trying to fetch the "Experience " key value .
Desired output :
name= Ruby
Experience = 5 years
My code :
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("path to JSON file"));
JSONObject jsonobj = (JSONObject) obj;
String statistics = jsonobj.getString("biodata"); //The method getString(String) is undefined for the type JSONObject
for (Iterator key = jsonobj.keys(); itr.hasNext();) {//The method keys() is undefined for the type JSONObject //itr cannot be resolved
JSONObject name = jsonobj.get(key.next()); //Type mismatch: cannot convert from Object to JSONObject
String key = key.next();//The method next() is undefined for the type String
JSONObject name = jsonobj.get(key); //Type mismatch: cannot convert from Object to JSONObject
Log.d("data", "key="+key+ " and value="+jsonobj.toString()); //Log cannot be resolved
}
I have mentioned the errors in the comment of my code .
You json is not valid .
You should change to this .
{
"biodata": {
"Ruby": {
"Expertise": "web development",
"EXperience": "5 years"
},
"Dylon": {
"Expertise": "Java",
"EXperience": "2 years"
}
}
}
Try this .
private void jsonParse() {
try {
// use jsonobject to parse json with
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("path to JSON file"));
JSONObject jsonObject = (JSONObject) obj;
// get jsonobject by biodata tag
JSONObject biodata = jsonObject.getJSONObject("biodata");
// use Iterator to get name
Iterator<String> names = biodata.keys();
// use while loop
while (names.hasNext()) {
// get name
String name = names.next().toString();
Log.d("data", "name=" + name);
// get jsonobject by name tag
JSONObject nameJsonObject = biodata.getJSONObject(name);
// get string
String Expertise = nameJsonObject.getString("Expertise");
String EXperience = nameJsonObject.getString("EXperience");
Log.d("data", "Experience =" + EXperience);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You have many issues in your code.
First: Assuming you want to implement code based on your current JSON String
Issues:
JSONObject API do not facilitate the methods of Map used in your implementation.
Your JSON String is not a array so for loop is not going to help, instead you should fetch the inner JSONObjects using the getJSONObject () method of the JSONObject API.
Casting the parsed object from your parser API will not automatically make it a JSONObject, the right way of doing this as below:
JsonObject jsonObject = parser.parse(new FileReader("path to JSON file")).getAsJsonObject();
Second: Assuming you intent to implement the JSON string representation as array, you should correct your JSON string as below.
"biodata": [{ "Ruby": { "Expertise": "web development", "EXperience": "5 years" }}, {"Dylon": { "Expertise": "Java", "EXperience": "2 years" } }]
With the above JSON string you can implement the fetching of data logic using JSONArray API
I have JsonElement like this:
{
"76800769": {
"prosjekLat": 45.784661646364,
"prosjekLong": 15.947804310909,
"brojCelija": 11
},
"76800772": {
"prosjekLat": 45.7847808175,
"prosjekLong": 15.9477082775,
"brojCelija": 4
},
"2946694": {
"prosjekLat": 45.78475167,
"prosjekLong": 15.9475975,
"brojCelija": 1
},
"76829440": {
"prosjekLat": 45.784726386,
"prosjekLong": 15.947961766,
"brojCelija": 5
}
}
I also create Model:
public class AddMarker {
int cellId;
double longitude;
double latitude;
}
I want to read JSON file and put values to List<AddMarker>.
I'm trying with this:
JsonElement data = response.body();
JsonObject obj = data.getAsJsonObject();
JsonArray arr = obj.getAsJsonArray();
but I'm getting an err: "This is not a JSON Array."
Your JSON is not an array.
Json Array syntax dictates that in order to have an array, your object must be formatted as:
[
{
...
},
{
...
},
...
{
...
}
]
Right now you have the outer square brackets ([]) as curly braces ({}). Change it to square brackets and your code should run correctly.
You're trying to make a array from a single object: JsonArray arr = obj.getAsJsonArray(), where obj is for exemple just this :
"76829440": {
"prosjekLat": 45.784726386,
"prosjekLong": 15.947961766,
"brojCelija": 5
}
you need to get the body from the response and make an array with all these objects, not from a single one
You can use this:
JsonObject json = new JsonObject(data);
String str1 = json.getString("76800769");
JsonObject json2 = new JsonObject(str1);
float str11 = json2.getFloat("prosjekLat");
Using org.json liberary, you can read the element as follows:
JSONObject obj = new JSONObject("your json element");
JSONObject obj2 = (JSONObject) obj.get("76800769");
System.out.println(obj2.get("brojCelija"));
System.out.println(obj2.get("prosjekLat"));
System.out.println(obj2.get("prosjekLong"));
which gives below output:
11
45.784661646364
15.947804310909
I need to convert JSON Object to array. In php just use array_values( $json ).
I solve my problem using this:
json_encode(array_values($izracunatProsjek), true);
I want to have a java list for all elements which are in the "in" or "out" element.
My json string:
{"in":[
{"id":4,"ip":"192.168.0.20","pinSysNo":4,"pinSysName":"pg6","folderName":"gpio4_pg6","alias":"d","direction":"digital_in"},
{"id":3,"ip":"192.168.0.20","pinSysNo":3,"pinSysName":"pb18","folderName":"gpio3_pb18","alias":"c","direction":"digital_out"}
],
"out":[
{"id":1,"ip":"192.168.0.20","pinSysNo":1,"pinSysName":"pg3","folderName":"gpio1_pg3","alias":"a","direction":"digital_in"},
{"id":2,"ip":"192.168.0.20","pinSysNo":2,"pinSysName":"pb16","folderName":"gpio2_pb16","alias":"b","direction":"digital_in"}
]
}:""
Until now I did this way:
String message = json.findPath("in").textValue();
But this way can only access to the first hierarchy.
My json example show two elements in the "in" element. How I can get a list of these internal "in" elements?
You could use the library JSONSimple in order to parse your JSON data by this code:
JSONParser parser = new JSONParser();
JSONObject o = (JSONObject) parser.parse(yourJsonAsString);
JSONArray ins = (JSONArray) o.get("in");
JSONArray outs = (JSONArray) o.get("out");
String firstIpAddress = ((JSONObject) ins.get(0)).get("ip").toString();
Thank you for your help. I found an other way to find all sub elements.
Json example:
{"in":[
{"id":4,"ip":"192.168.0.20","pinSysNo":4,"pinSysName":"pg6","folderName":"gpio4_pg6","alias":"d","direction":"digital_in"},
{"id":3,"ip":"192.168.0.20","pinSysNo":3,"pinSysName":"pb18","folderName":"gpio3_pb18","alias":"c","direction":"digital_out"}
],
"out":[
{"id":1,"ip":"192.168.0.20","pinSysNo":1,"pinSysName":"pg3","folderName":"gpio1_pg3","alias":"a","direction":"digital_in"}
,{"id":2,"ip":"192.168.0.20","pinSysNo":2,"pinSysName":"pb16","folderName":"gpio2_pb16","alias":"b","direction":"digital_in"}
]
}
My solution:
JsonNode json = request().body().asJson();
Logger.info("JSON : " + json.findPath("in").findPath("id"));
Logger.info("JSON : " + json.findValues("in"));
List<JsonNode> ins = new org.json.simple.JSONArray();
ins = json.findValues("in");
for (final JsonNode objNode : ins) {
for (final JsonNode element : objNode) {
Logger.info(">>>>>" + element.findPath("id"));
//create my object for database
}
}
Now I can create my Object for the database.
#eztam thank you