Sample code for 30+ languages & platforms
Java

JSON Copy Objects

See more JSON Examples

Copy objects from one JSON document to another.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.JsonObject;

public class ChilkatExample {

    public static void main(String[] args) {
        JsonObject json1 = new JsonObject();
        json1.updateString("ID1.cn", "Name");
        json1.updateString("ID1.objectGUID", "GUID");
        json1.updateString("ID2.cn", "Name");
        json1.updateString("ID2.objectGUID", "GUID");

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

        // json1 contains:
        // {
        //   "ID1": {
        //     "cn": "Name",
        //     "objectGUID": "GUID"
        //   },
        //   "ID2": {
        //     "cn": "Name",
        //     "objectGUID": "GUID"
        //   }
        // }

        JsonObject json2 = new JsonObject();
        json2.updateString("Name1.ID1.cn", "Name");
        json2.updateString("Name1.ID1.objectGUID", "GUID");
        json2.updateString("Name1.ID2.cn", "Name");
        json2.updateString("Name1.ID2.objectGUID", "GUID");
        json2.updateString("Name2.ID3.cn", "Name");
        json2.updateString("Name2.ID3.objectGUID", "GUID");

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

        // {
        //   "Name1": {
        //     "ID1": {
        //       "cn": "Name",
        //       "objectGUID": "GUID"
        //     },
        //     "ID2": {
        //       "cn": "Name",
        //       "objectGUID": "GUID"
        //     }
        //   },
        //   "Name2": {
        //     "ID3": {
        //       "cn": "Name",
        //       "objectGUID": "GUID"
        //     }
        //   }
        // }

        // Copy Name1, Name2 into json1

        int i = 0;
        int numMembers = json2.getSize();
        while (i < numMembers) {
            JsonObject jsonObj = json2.objectAt(i);
            json1.appendObjectCopy(json2.nameAt(i), jsonObj);
            i = i + 1;
        }

        // Now see what json1 contains:
        System.out.println(json1.emit());

        // {
        //   "ID1": {
        //     "cn": "Name",
        //     "objectGUID": "GUID"
        //   },
        //   "ID2": {
        //     "cn": "Name",
        //     "objectGUID": "GUID"
        //   },
        //   "Name1": {
        //     "ID1": {
        //       "cn": "Name",
        //       "objectGUID": "GUID"
        //     },
        //     "ID2": {
        //       "cn": "Name",
        //       "objectGUID": "GUID"
        //     }
        //   },
        //   "Name2": {
        //     "ID3": {
        //       "cn": "Name",
        //       "objectGUID": "GUID"
        //     }
        //   }
        // }
    }
}