My JSON file contains several attributes. One of them is a list of objects. I need to access this list via a numerical key, ie the 1st, the 2nd etc element.
When getting the nth element I want to access its attributes by a alphabetical key.
Example:
MyObj.get("itemlist").get(0).get("attribute")
If I do this I'm forced to convert the whole thing to an JSONArray from which (afaik) I can't access my attributes via a key but just by position.
Here's my JSON string:
{
"id": 1,
"items": [
{
"id": 1,
"type": "video",
"name": "test.mp4"
},
{
"id": 2,
"type": "image",
"name": "pic.jpg"
}
],
"name": "test"
}
Any ideas?
Ok, don't quite understand why but when I do the following it works:
JSONArray MyList = new JSONObject(filePath).getJSONArray("items");
System.out.println((((JSONObject) MyList.get(1)).get("type")));
So I just omitted the MyObj and targeted the list directly.
Related
I am using jsonschema2pojo (via gradle) to generate pojo from an external json schema that has a property (inside another property of type "object") with the following definition (field names and values changed but all types are identical):
"alternativeText": {
"type": "array",
"items": [{
"type": "object",
"required": [
"code",
"language",
"value"
],
"properties": {
"code": {
"type": "integer",
"enum": [1, 2, 3, 4]
},
"language": {
"type": "string",
"enum": ["de-DE", "en-US"]
},
"value": {
"type": "string"
}
}
}],
which generates the following java code
#JsonProperty("alternativeText")
#Valid
#NotNull
private List<Object> alternativeText = new ArrayList<Object>();
#JsonIgnore
#Valid
private Map<String, Object> additionalProperties = new LinkedHashMap<String, Object>();
This interface is not ideal, especially when the consumer is going to validate against the enum values for "code" and "language".
We have similar issues when an enum is in an array, then the API generates List<Object> instead of e.g. List<SomeEnumType>.
Is there anything that can be configured to improve the semantics of the generated code? For other properties with "enum" (and object for that matter!) it works correctly, it seems like the array of enum or array of objects gets overly simplified.
It looks like you have accidentally used the (old) tuple syntax for items. Try replacing this:
"items": [{
with this
"items": {
Your items schema should not be inside an array.
I am currently saving a JSON response in a map and I'm struggling iterating over the nested HashMap values. For example:
Index 0
Index 1 -> Key: "Example":
Key: "Example 2"
Values "Example 3" (ArrayList)
Key, Values... (HashMap)
My map looks like:
HashMap<Object, Object> map = (HashMap< Object, Object >) result.getBody();
Which is saving the result from the following Spring Boot ResponseEntity:
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Object> result = restTemplate.exchange(url, HttpMethod.GET,
entity, Object.class);
And to iterate over the first set of indexes I am doing:
for (Map.Entry<Opportunities, Opportunities> entry : resultMap.entrySet()) {
System.out.println(entry.getValue());
}
How can I iterate over the values inside Index 1? I have tried adapting this solution but with no luck.
Thanks in advance.
Edit - The JSON response looks like:
{
"metadata": {
"page": 0,
"pageSize": 1,
"pageCount": 10,
"totalCount": 10
},
"Users": [
{
"ID": 1216411,
"name": "John",
"name": "John",
"Order_Details": {
"id": 1216411234,
"item": "Electric Razer",
"region": {
"name": "United States",
"regionCode": "US"
}
},
"Suppliers": [
...
So assuming you have something like this.
Map<String,LinkedHashMap<String,Long>> map =...
for (Map<String,Long> lhms : map.values()) {
for (long value : lhms.values()) {
System.out.println(value);
}
}
WJS gave a very good response for the question you asked ...
... but it definitely sounds like you might want to revisit your "design".
Specifically, how do you want to map your JSON data to Java objects?
As Pshemo said, HashMaps are great for fast lookup of a given key ... but you can't easily iterate over the list in the same order you created it.
There's also the question of how "simple" or "complex" you want to make your "nested data".
All of which will affect how easy it is to create, read and/or update your list.
Strong suggestion: consider using Jackson:
https://www.baeldung.com/jackson-object-mapper-tutorial
Hi I am trying to compare fileds of two json objects and have to duplicates in json array.
below is my input which is json array of two json objects. both of the json objects have same tag called Architectural this has to be avoided and
I want to make single json object with array of filenames without duplicates and filesize
in the array of json objects, each object may contain name json array with different length
[ {
"bucket": "vanasiri-100-98748-33434346-34545567002",
"path": "1127/1854/1/BidSet/Architectural_Drawing/",
"UpdatedBy": "100",
"fileSize": ["0"],
"name": ["Display external company list.docx"],
"tag": "Architectural",
"uploadedDate": "03-30-2019"
}, {
"bucket": "vanasiri-100-98748-33434346-34545567002",
"path": "1127/1854/1/BidSet/Architectural_Drawing/",
"UpdatedBy": "100",
"fileSize": ["0"],
"name": ["images.jfif"],
"tag": "Architectural",
"uploadedDate": "03-30-2019"
}
]
Expected result
[{
"bucket": "vanasiri-100-98748-33434346-34545567002",
"path": "1127/1854/1/BidSet/Architectural_Drawing/",
"UpdatedBy": "100",
"fileSize": ["0", "0"],
"name": ["Display external company list.docx", "images.jfif"],
"tag": "Architectural",
"uploadedDate": "03-30-2019"
}]
How can i achieve this
Create a Model class say BucketData for the JSON Object inside your list and you can convert the JSON array to an Array List of Models.
Should looks something like below:
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.getString(i));
}
}
Then you can perform Java 8 Filter operation to filter out the duplicate values as below:
List listdata = listdata.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BucketData:: getTag))),
ArrayList::new));
Referred from https://stackoverflow.com/a/17037364/4597596 and https://stackoverflow.com/a/55512294/4597596
In my opinion, you should first convert the JSON array into a SET; a HASHSET to be precise. HASHSET does not allow you to store a duplicate element.
Now, how to convert an array into hashset? please refer one of the older discussion on this forum - How to convert an Array to a Set in Java
I am new to java programming, I am not getting the right example for my below nested json object scenario, Here is my Json object which I have, how can I update the "stackoverflow" values 1 with 100 and 2 with 200 etc.
also stackoveflow is incremental json object it can be {} or {...}, in below i given size of 2 elements . how can I update/replace this jsonobject faster and efficient way without effecting other objects. Thanks Much
{
"name": "sample",
"stackoverflow":
{
"one": {
"name": 1,
"type": "number",
"value":"onevalue"
},
"two": {
"name": 2,
"type": "number",
"value":"twovalue"
},
},
}
I want to compare two JsonObjects (GSON) in Java in such a way that I can ignore some predefined nodes like timestamp, id, etc.
Here is example JsonObject:
Object 1:
{
"id": "uid1",
"name": "name",
"data": {
"timestamp": "timestamp1",
"properties": {
"id": "propId1",
"propertyName": "propertyValue"
}
}
}
Object 2:
{
"id": "uid2",
"name": "name",
"data": {
"timestamp": "timestamp2",
"properties": {
"id": "propId2",
"propertyName": "propertyValue"
}
}
}
In above JsonObjects the comparison should result as identical. "id" and "timestamp" should be ignored.
Since my JsonObjects are nested and complicated I am trying to find a way I could do it avoiding to iterate all nodes. Using "equals" will right now give identical as false.
If these objects are mapped to some entity in your application, you can write a Comparator which compare the equality of two objects based on your criteria of equality