0

How do I add jsonArray data into an ArrayList of type Product.

I wrote a test class with dummy json data. The main class is as follows:

public class convertData {

        public static void main(String[] args) {

            List<ProductModel> myList = new ArrayList<>();

            JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
            JsonObject jsonObject1, jsonObject2, jsonObject3;


            jsonObject1 = Json.createObjectBuilder()
                    .add("id", 1)
                    .add("name", "Albany")
                    .add( "manufacture", "Albany Superior Low Gi Sliced Brown Seed Bread 700g")
                    .add("price", 15.49)
                    .add("category", "Food")
                    .add ("type", "Breads")
                    .add( "image", "data:image/jpeg;base64,/9j/4A" )
                    .build();

            jsonObject2 = Json.createObjectBuilder()
                    .add("id", 1)
                    .add("name", "Albany")
                    .add( "manufacture", "yuyyjjgyced Brown Seed Bread 700g")
                    .add("price", 15.49)
                    .add("category", "Food")
                    .add ("type", "Breads")
                    .add( "image", "data:image/jpeg;base64,/9j/4A" )
                    .build();

            jsonObject3 = Json.createObjectBuilder()
                    .add("id", 1)
                    .add("name", "Albany")
                    .add( "manufacture", "Albany Superior Low Gi Sliced Brown Seed Bread 700g")
                    .add("price", 15.49)
                    .add("category", "Food")
                    .add ("type", "Milk")
                    .add( "image", "data:image/jpeg;base64,/9j/4A" )
                    .build();


            arrayBuilder.add(jsonObject1);
            arrayBuilder.add(jsonObject2);
            arrayBuilder.add(jsonObject3);

            JSONArray jArray = (JSONArray) arrayBuilder; 

            if (jArray != null) { 

                for (int i=0;i<jArray.length();i++){ 
                    myList.add(jArray.get(i));
                }
            }

        }
    }

I then created a product model class as follows:

class ProductModel {

            private int id;
            private String name;
            private String manufacture;
            private Double price;
            private String category;
            private String type;
            private String image;
            // get and setters
            ...

I have searched for similar solution, but there were not helpful in a way.

The project is written using J2SE platform, and I only added the jar files for json.

The json data I am building looks something like these:

[
    {
        "id": 1,
        "name": "Albany",
        "manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g",
        "price": 15.49,
        "category": "Food",
        "type": "Breads",
        "image": "data:image/jpeg;base64,/9j/4..."
    },
    {
        "id": 2,
        "name": "Blue Ribbon",
        "manufacture": "Blue Ribbon Brown Plus Low Gi Bread 700g",
        "price": 13.99,
        "category": "Food",
        "type": "Breads",
        "image": "data:image/jpeg;base64,/9j/4AAQSkZ."
    },
    {
        "id": 3,
        "name": "Cheese",
        "manufacture": "Galbani Mozzarella Cheese 300g",
        "price": 49.99,
        "category": "Food",
        "type": "Cheese",
        "image": "data:image/octet-stream;base64,/9j/4AAQSkZJRg..."
    }
]
1
  • your question is unclear, is the jsonArray a member of ProductModel class? would be better if you share the expected output as it would look like in the end. Commented Feb 13, 2018 at 8:30

3 Answers 3

2

A few chnages needs to be done to make it run:

  1. Add a constructor in ProductModel class that will accept JsonObject as argument:

    public ProductModel(JsonObject json) {
        super();
        this.id = json.getInt("id");
        this.name = json.getString("name");
        this.manufacture = json.getString("manufacture");
        this.price = Double.parseDouble(json.getJsonNumber("price").toString());
        this.category = json.getString("category");
        this.type = json.getString("type");
        this.image = json.getString("image");
    }
    
  2. use JsonArray instead of JSONArray and pass build array to it:

    JsonArray jArray = arrayBuilder.build();
    
  3. call newly created constructor in add method:

    if (jArray != null) { 
    
             for (int i=0;i<jArray.size();i++){ 
                 myList.add(new ProductModel((JsonObject) jArray.get(i)));
             }
         }
    
Sign up to request clarification or add additional context in comments.

Comments

0

You can convert each JsonObject individually into a ProductModel object by doing something like this:

new com.fasterxml.jackson.databind.ObjectMapper().readValue(jsonObject.toString(), ProductModel.class);

Then you can easily add these objects into ProductModel type array.

3 Comments

What I want to do is to add that the jsonArray all-in-all into arrayList and not jsonObject separately.
He seems to be using json-simple library. Not Jackson.
666DESH666 You can iterate on your jsonArray and convert each entry into a ProductModel object. You can use a simple loop or stream.
0

To be easier to get help, you should explain what libraries you are using. There is one link you have put there to an example that is using json-simple so I will assume you use it as well.

Although simple, this library seems to not be documented and just a very few examples out there. Also not that many futures in it (like the one that you are after: to convert the json into a Java object).

One valid option is to use a better documented library for JSON, like Jackson or GSON.

If you want to continue with this, you can write specific adapter to transform JsonObject to ProductModel. Or a more general adapter using reflection to transform JsonObject to a java bean class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.