I am trying to define java generic type in method and I am not able to do so. I went through lot of posts but haven't figured it out.
I have a JSON which will be converted to java LinkedHashMap by Mule Dataweave. Here is simple JSON
{
"a": {
"b": {
"c": [{
"name": "abc"
},
{
"name": "xyz"
}
],
"d": "e"
},
"f": "g"
}
}
Now I want to use that JSON converted to LinkedHashMap in java method.
I tried something like
public void test(LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap>> payload)
but the value can be recursive LinkedHashMap until I get key and value as String. I don't know how deep it can go as it is based on JSON response. How can I define it in java generics?
As Java Does not support Union Types you can not model this other than
public void test(LinkedHashMap<String, Object> payload)
Where you know that an Object is Either a Map<> or String or List.
Related
I have a json that looks something like this
{
"a": {
"b": [
{
"c": {
"d": [{ "f": "value" }]
}
},
{
"c": {
"d": [{ "f": "value" }]
}
}
]
}
}
I'm looping the data inside b using the following code, then getting the array at d again in a nested loop
for (JsonNode abNode : rootNode.at("/a/b")) {
for (JsonNode cdNode : abNode.at("/c/d")) {
//cdNode.get("f")
}
}
Inside the for loop how can I get the path of something like node.get("f") so that I would get /a/b/0/c/d/0/f and then /a/b/1/c/d/0/f? Does jackson have something to get this or another library? The only thing I can think of right now is just switching to a for i=0 loop
What you are trying to do is also called as Xpath in technical terms.
It is used for html, xml based languages as well as now available in json
You can try jsonpath for this case:
https://www.baeldung.com/guide-to-jayway-jsonpath
https://github.com/json-path/JsonPath
Google's popular GSON library has a method, namely getPath, maybe useful for your purpose:
String json = "...";
JsonReader reader = new JsonReader(new StringReader(json));
System.out.println(reader.getPath());
I'm struggling to find a solution for this...
I would like to know how to get a specified parameter passing it through the request without having to code each specific case in Spring Boot API.
For example, in my case I have this JSON object:
{
"id": 3,
"name": "test",
"dominio": "dom",
"altas": "6",
"bajas": "2",
"default_group": [
{
"idRef": 1,
"name": "Users",
"path": "OU=es"
}
],
"office": [
{
"idRef": 1,
"title": "Intern",
"name": "CN=Office license",
"path": "OU=licenseOffice"
},
{
"idRef": 2,
"title": "Specialist",
"name": "CN=Office License F3",
"path": "OU=LicenseGroupF"
}
]
Apart from this, I have all the entities defined in my code, but I would like to access one of their parameters just using their names, like name, dominio, altas, bajas, default_group or office.
The idea is to do this without having to code each method for each parameter.
I wouldn't have to do this for the nested objects (office and default_group) just getting the info from them passing the name of the parameter.
So I would like to do something like:
GET --> localhost:8080/api/3/name
And this would return the name of object with id 3
Or doing this:
GET --> localhost:8080/api/3/default_group
And this would return the Array containing all the default_groups inside.
Apart from this, I would like to know if is it possible to do a PUT request for the methods doing the same thing.
I don't know if this can be done, but in case that it can, would it be possible for you to give some guidance or something...
Thank you very much
Edit. Thanks to #daniu I made it work flawlessly, I paste my solution here based on his comment so if anybody find it helpful. My object is called "Compania".
#GetMapping("/{companiaId}/{field_name}")
public Object queryField(
#PathVariable("companiaId") Long companiaId,
#PathVariable("field_name") String fieldName) {
Map<String, Function<Compania, Object>> fieldRetrievers = Map.of(
"name", Compania::getName,
"dominio", Compania::getDominio,
"altas", Compania::getAltas,
"bajas", Compania::getBajas,
"default_group", Compania::getDefault_group,
"office", Compania::getOffice
);
Compania c = companiaService.getCompaniaNotOpt(companiaId);
Function<Compania, Object> retriever = fieldRetrievers.get(fieldName);
return retriever.apply(c);
}
getCompaniaNotOpt is a method that takes a Compania without being Optional, so it works.
Thanks daniu.
I wouldn't consider this the cleanest of designs, but what would work is creating a Map that contains all the field accessors by name:
Map<String, Function<YourClass>> fieldRetrievers = Map.of(
"name", YourClass::getName,
"default_group", YourClass::getDefaultGroup,
"office", YourClass::getOffice
);
Then you can use that in your controller (service actually, but to keep it short here):
#GetMapping("/path/{field_name}")
Object queryField(#PathVariable("field_name") String fieldName) {
YourClass c = getObject();
Function<YourClass, Object> retriever = fieldRetrievers.get(fieldName);
return retriever.apply(c);
}
anyone know how can I convert this Java List Object to Json?
List<SampleObject> sample = new ArrayList<SampleObject>();
to this format (notice that the Json is not an array)
{
"0": {
"firstName": "",
"lastName": "",
},
"1": {
"firstName": "",
"lastName": "",
}
}
Thanks in advance. Hope you can help me :)
Convert your List to Map, where your key would be an Integer representing 0-based index in your list. After that convert your map to JSON by any standard way and you will get your format. To see how to serialize your Map (or any class) to JSON see this question: How to serialise a POJO to be sent over a Java RSocket?
Is there a library or a simple recursive way to get all the property values (without property names or json specific characters) from a random json?
For example, from this object:
{
"a": "aVal",
"b": {
"b1": "b1Val"
},
"c": [
"cVal",
{
"c1":"c1Val"
},
[["c3Val"]]
]
}
I need the values marked with the Val suffix: aVal, b1Val, cVal, c1Val, c3Val
You can use org.json library.
pass the JSON string in a constructor and work with objects after that. Info
Example:
JSONObject root = new JSONObject("{\"a\": \"aVal\",\"b\": {\"b1\": \"b1Val\"},\"c\": [\"cVal\",{\"c1\":\"c1Val\"},[[\"c3Val\"]]]}");
for (Object objKey : root.names()) {
//do things here..
}
When reading facebook graph api insights response it can have two types of response
"data":{
"name": "page_posts_impressions",
"values": [
{
"value": 10,//integer value
"end_time": "2019-07-29T07:00:00+0000"
}
]
}
here inside values, value has integer value but in another case
"data":{
"name": "page_posts_impressions",
"values": [
{
"value": { "post":10,
"tab":1
}//json object value
"end_time": "2019-07-29T07:00:00+0000"
}
]
}
here value has json object value, how can I parse these king of json object ?
I believe you are going to parse this JSON to java POJO. Since values is Array of Objects i will suggest to parse that into JsonNode, which is
List<JsonNode> values;
Advantage's in this approach is JsonNode has couple of method to find whether it is Integer or JsonObject
isInt()
public boolean isInt()
isObject
public final boolean isObject()