0

Any idea how I can parse a Json like this into a java entity?

{
      "-MR0myiEK5jDOdthWeMT": {
        "birthday": "Date5",
        "name": "Check 1"
      },
      "-MR0n-86JCqxuO7C2HfZ": {
        "birthday": "Date3",
        "name": "Check 2"
      },
      "-MR0n0VCXBw-32tfq738": {
        "birthday": "Date1",
        "name": "Check 4"
      }
    }

I am using spring and wanted to parse it into a java class like this:

class Person{
   String name;
   String birthday;
} 

2 Answers2

0

The org.json library is easy to use.

Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation

[ … ] represents an array, so library will parse it to JSONArray { … } represents an object, so library will parse it to JSONObject Example code below:

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("birthday");
    ......
}
-2

I would use the

jackson

library that is already included in the spring boot dependencies.

lukaneto
  • 1
  • 1