0

I have a simple API on nodejs that stores MongoDB documents. I have an API endpoint that retrieves documents in a json array.

I want to implement a client for this API in Java. Since Java supports reflection, I should't need to map each json document from the array into a java object with the same fields. There must be a way that simply maps one to another. However, it must support nested objects. Here's my object in Java:

public class Order {
    public Boolean deleted;
    //Use only when updating an order, _id is mongo's _id of order to be updated
    public String _id;
    static public class Product {
        public String name;
        public Integer quantity;
        public Float price;
    }
    public String clientName;
    public String clientPhone;
    public Integer seller_id;
    public Integer order_id;
    public String observations;
    public ArrayList<Product> products = new ArrayList<Product>();
    public Float total;
}

The Json Array that I receive from the API will have the same members: clientName, clientPhone, products, etc. I just need to map the Json Array element to Order.

There's a library that supports reflection (Jackson) and gives me a way to do the inverse: Order to Json, but I couldn't find a way to do what I want.

1
  • 2
    Jackson supports both serialization and deserialization. So does Gson. Commented Jan 23, 2020 at 3:46

1 Answer 1

1

Using Jackson, you can convert json to java object in following way.

//json variable is the String represenating the json you have received from API
Order order = new ObjectMapper().readValue(json, Order.class);

For more examples you can check Jackson examples

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.