Sample code for 30+ languages & platforms
Java

Build JSON with Mixture of Arrays and Objects

See more JSON Examples

Another example showing how to build JSON containing a mixture of arrays and objects.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.JsonObject;

public class ChilkatExample {

    public static void main(String[] args) {
        // We want to build the following JSON:

        // {
        //   "accountEnabled": true,
        //   "assignedLicenses": [
        //     {
        //       "disabledPlans": [ "bea13e0c-3828-4daa-a392-28af7ff61a0f" ],
        //       "skuId": "skuId-value"
        //     }
        //   ],
        //   "assignedPlans": [
        //     {
        //       "assignedDateTime": "datetime-value",
        //       "capabilityStatus": "capabilityStatus-value",
        //       "service": "service-value",
        //       "servicePlanId": "bea13e0c-3828-4daa-a392-28af7ff61a0f"
        //     }
        //   ],
        //   "businessPhones": [
        //     "businessPhones-value"
        //   ],
        //   "city": "city-value",
        //   "companyName": "companyName-value"
        // }

        JsonObject json = new JsonObject();
        json.updateBool("accountEnabled", true);
        json.setI(0);
        json.updateString("assignedLicenses[i].disabledPlans[0]", "bea13e0c-3828-4daa-a392-28af7ff61a0f");
        json.updateString("assignedLicenses[i].skuId", "skuId-value");
        json.updateString("assignedPlans[i].assignedDateTime", "datetime-value");
        json.updateString("assignedPlans[i].capabilityStatus", "capabilityStatus-value");
        json.updateString("assignedPlans[i].service", "service-value");
        json.updateString("assignedPlans[i].servicePlanId", "bea13e0c-3828-4daa-a392-28af7ff61a0f");
        json.updateString("businessPhones[i]", "businessPhones-value");
        json.updateString("city", "city-value");
        json.updateString("companyName", "companyName-value");

        json.setEmitCompact(false);
        System.out.println(json.emit());

        // Output:

        // {
        //   "accountEnabled": true,
        //   "assignedLicenses": [
        //     {
        //       "disabledPlans": [
        //         "bea13e0c-3828-4daa-a392-28af7ff61a0f"
        //       ],
        //       "skuId": "skuId-value"
        //     }
        //   ],
        //   "assignedPlans": [
        //     {
        //       "assignedDateTime": "datetime-value",
        //       "capabilityStatus": "capabilityStatus-value",
        //       "service": "service-value",
        //       "servicePlanId": "bea13e0c-3828-4daa-a392-28af7ff61a0f"
        //     }
        //   ],
        //   "businessPhones": [
        //     "businessPhones-value"
        //   ],
        //   "city": "city-value",
        //   "companyName": "companyName-value"
        // }
    }
}