matthewoak
matthewoak

Reputation: 49

How to add an empty JSON Array to JSON Object in a specific order

I am trying to create this structure for a JSON -


    {
      "pricing": {
        "quantity": 4200,
        "minQuantity": 10,
        "pricePerUnit": {
          "amount": 0.2865,
          "currency": "USD"
        },
        "discounts": []
      },
      "description": "test",
      "guaranteedDeliveryTime": "testTime",
      "offerType": "Currency"
    }

I have came up with a solution that is pretty close. However the ordering seems a bit off. Here is the code I am using -

Map<String, Object> pricePerUnit = new LinkedHashMap<>();
    pricePerUnit.put("amount", 0.2865);
    pricePerUnit.put("currency", "USD");

    Map<String, Object> pricing = new LinkedHashMap<>(8, 0.6f, false);
    pricing.put("quantity", 2342);
    pricing.put("minQuantity", 2342);
    pricing.put("pricePerUnit", pricePerUnit);
    pricing.put("discounts", new JSONArray());

    JSONObject obj1 = new JSONObject();
    obj1.put("pricing", pricing);
    obj1.put("guaranteedDeliveryTime", "testTime");
    obj1.put("description", "test");
    obj1.put("offerTime", "Currency");

And the final output is as follows.

    {
      "guaranteedDeliveryTime": "testTime",
      "description": "test",
      "pricing": {
        "quantity": 2342,
        "minQuantity": 2342,
        "discounts": [],
        "pricePerUnit": {
          "amount": 0.2865,
          "currency": "USD"
        }
      },
      "offerTime": "Currency"
    }

The ordering seems off. I assume it is an issue as I am using a LinkedHashMap. I also tried setting the access order to see if that would change the ordering. Any advice would be greatly appreciated. Thanks.

Upvotes: 1

Views: 92

Answers (1)

devwebcl
devwebcl

Reputation: 3203

A JSONObject is an unordered collection of name/value pairs.

https://www.javadoc.io/doc/org.json/json/20171018/org/json/JSONObject.html

Upvotes: 1

Related Questions