Home > OS >  Using Jackson, how can you get a list of objects from an interesting json?
Using Jackson, how can you get a list of objects from an interesting json?

Time:01-13

I have this json, I need to get a list of currency objects using Jackson (the objects itself has a currency name field - "USD", "type" and "show") as a result. How can I do it in a simple and clear way?

Any help would be welcome

{
    ...
    "result": "OK",
    "currency": {
        "currencies": {
            "LB": {
                "type": "A",
                "setting": {
                    "show": true,
                },
                "access" : true
            },
            "USD": {
                "type": "B",
                "setting": {
                    "show": true,
                },
                "access" : true
            },
            "RUB": {
                "type": "A",
                "setting": {
                    "show": true,
                },
                "access" : true
            },
          ....
          // and more.. 
         },
       ...
    }
 }

CodePudding user response:

"currencies": {
        "LB": {
            "type": "A",
            "setting": {
                "show": true,
            },
            "access" : true
        },
        "USD": {
            "type": "B",
            "setting": {
                "show": true,
            },
            "access" : true
        },
        "RUB": {
            "type": "A",
            "setting": {
                "show": true,
            },
            "access" : true
        },
      ....
      // and more.. 
     },
   ...

This looks like an Map, not a List. Does that help you? So you would need to create Currency class and have jackson parse this structure to Map<String, Currency>. Note that currency will not contain the identifier (like "USD"), only they key in the map will.

CodePudding user response:

You can read your Json as a Map<String, Object>. Once you have the map you iterate through your map and build your List. If you want to de-serialize (read) from Json to List of your custom objects you need to have your Json restructured to be Json List and not Json Object. Then you can read your Json into a List directly.

In any case, there is an Open source Library that has a feature based on Jackson library really simplifies reading/writing objects from/to Json. If you have a json string all you have to do is:

Map<String, Object> map = JsonUtils.readObjectFromJsonString(jsonString, Map.class);

It throws IOException though, so you will need to handle it. Here is the Javadoc. The library is called MgntUtils and could be found as Maven artifact and on the Github (including javadoc and source code)

  •  Tags:  
  • Related