0
votes

I'm trying to map the following json via jackson to a pojo. I have the first part working (up until section). However, the second part I'm not sure how I can map "section1" to perhaps a contained pojo or best practice here?

json received via rest call:

{
   "val1":100,
   "val2":2.75,
   "junk":[
      {
         "junk1":36,
         "junk2":78
      },
      {
         "junk1":36,
         "junk2":78
      }
   ],
   "section1":{     // <- There will be another section2, section3,...
      "val1":100,
      "val2":2.75,
      "junk1":[
         {
            "junk1":36,
            "junk2":78
         },
         {
            "junk1":36,
            "junk2":78
         }
      ],
      "junk2":[
         {
            "junk1":36,
            "junk2":78
         },
         {
            "junk1":36,
            "junk2":78
         }
      ]
   }
}

Pojo:

public class view
{
    private int val1;
    private float val2;
    private List<Map<String, String> > junk; //<-Ok as I just pass to another class

        // How to store "section" ... and want to keep junk1, junk2 same
        // placeholder like I have for junk in main section above.


}
2
your JSON will not result into a gud object... do u have a limit on section numbers or junk numbers?dharam

2 Answers

1
votes

Make 'section' another class and also 'junk' if the contents of each section (and each piece of junk) has the same structure internally.

public class view
{
    private int val1;
    private float val2;
    private List<Junk> junk; //<-Ok as I just pass to another class
    private Section section1;
    private Section section2;
    ... etc ...
}

public class Section {
   private int val1;
    private float val2;
    private List<Junk> junk; //<-Ok as I just pass to another class
}

public class Junk {
   private String junk1;
   private Strign junk2;
}

I'm assuming the structure you showed as opposed to an array of sections.

Plus a map isn't a good place to store two random strings. But Jackson will allow it. The only exception is if the names of the fields will vary from 'junk1' and 'junk2'. Otherwise just use a class with two strings in it.

1
votes

Note that you can indicate that "junk" should be ignored. There are couple of ways to do it; one is to do:

@JsonIgnoreProperties({"junk"})
public class MyClass { ... }

this has the benefit of not requiring memory to store matching data; and it can speed up parsing a bit (not a ton, but some; parser still needs to decode JSON to skip it etc).