Search code examples
javajsondata-structuresassociative-array

Is there a data-structure similar to JSON in JAVA?


I need to store key-value pairs inside key-value pairs and so on as required by the data.

I tried to achieve this using Hash-Map in java but it didn't work as I expected it to. Since, my data has multiple name->value pairs, but the Hash-Map keeps overwriting the name key's value with the new one.

Say for example, I need to store a list of products and their details for an online store. Which data structure would help me achieve this and how ?

TIA.


Solution

  • If you want a 'generic' collection, why not use a Guava MultiMap ?

    A collection that maps keys to values, similar to Map, but in which each key may be associated with multiple values. You can visualize the contents of a multimap either as a map from keys to nonempty collections of values ... or as a single "flattened" collection of key-value pairs

    However, it sounds like you may really want to model your entities as proper objects, with the appropriate attributes etc. Storing collections of collections of collections will work, but you'll lose some of the benefits of defining objects with behaviour/polymorphism etc.

    e.g.

    List<Product> products = ...
    products.add(new Book(...));
    products.add(new Dvd(...));
    

    (or perhaps a map of stock item id to object instance, or, or, or...)

    I would treat JSON as a representation of your object (e.g. like XML). If you need to transport or store these objects, translate them to a format such as JSON or XML. But manage them within your program using objects with type and behaviour.