0

I am looking for a JSON library for Java, which allows multiple objects of the same class to be stored in a JSON file, which can then be deserialized by their ID. For example like this:

GroceriesPerDay.json:

{
  "monday" {
        "apples": "5"
        "bananas": "5"
  },
  "tuesday" {
        "apples": "2"
        "bananas": "6"
  }
}

After deserialization these values should be stored in an object of the class "Groceries" with the attributes "apples" and "bananas" (if their ID would have to be stored as well, that's fine). I can not find a fitting one for the life of me. Any suggestions?

  • Answer to your question can be found here : [https://stackoverflow.com/a/33759662/7027154](https://stackoverflow.com/a/33759662/7027154) – Ankit Gupta Jul 17 '20 at 10:16
  • Welcome to Stack Overflow! Please take the [tour] (you get a badge!), have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask), [*What types of questions should I avoid asking?*](/help/dont-ask), and [*What topics can I ask about here?*](/help/on-topic) – T.J. Crowder Jul 17 '20 at 10:16
  • Isn't the answer *literally all of them*? – user253751 Jul 17 '20 at 10:19

1 Answers1

0

As comments suggest the problem is not what library to choose but more like what data structure you should use. First of all your example JSON is malformed and needs some fixes.

After that you can deserialize it as a specialized map. My example is for GSON but should be easily applied to Jackson also.

Fixed JSON

String JSON = "{" + 
                  // v missing ":"
        "  \"monday\": {" + 
                               // v missing ","
        "        \"apples\": \"5\"," + 
        "        \"bananas\": \"5\"" + 
        "  }," + 
                   // v missing ":"
        "  \"tuesday\": {" + 
                               // v missing ","
        "        \"apples\": \"2\"," + 
        "        \"bananas\": \"6\"" + 
        "  }" + 
        "}"; 

Now, if define Groceries like:

@Getter @Setter
public static class Groceries {
    private int apples;
    private int bananas;        
}

and also create a specialized Map like

@SuppressWarnings("serial")
public class GroceriesMap extends HashMap<String, Groceries> {};

(you can also use TypeToken with GSON to handle generics but I think it is a matter of taste, use TypeToken if not willing to extend HashMap an create ne classes)

After that it is just:

GroceriesMap map = gson.fromJson(JSON, GroceriesMap.class);
Groceries monday = map.get("monday");
Groceries tuesday = map.get("tuesday");
pirho
  • 11,565
  • 12
  • 43
  • 70