Java Requires Chilkat v11.0.0+
Chilkat2 Java
Swap JSON Objects
See more JSON Examples
Demonstrates how to swap two JSON objects within a JSON document.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
public class ChilkatExample {
public static void main(String[] args) {
JsonObject json = new JsonObject();
json.setEmitCompact(false);
// Load the following JSON:
// {
// "petter": {
// "DOB": "26/02/1986",
// "gender": "male",
// "country": "US"
// },
// "Sara": {
// "DOB": "13/05/1982",
// "gender": "female",
// "country": "FR"
// },
// "Jon": {
// "DOB": "19/03/1984",
// "gender": "male",
// "country": "UK"
// }
// }
try {
json.loadFile("qa_data/json/people.json");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Swap the positions of Jon and Sara.
int index1 = json.indexOf("Jon");
int index2 = json.indexOf("Sara");
json.swap(index1, index2);
// We have this now:
System.out.println(json.emit());
// {
// "petter": {
// "DOB": "26/02/1986",
// "gender": "male",
// "country": "US"
// },
// "Jon": {
// "DOB": "19/03/1984",
// "gender": "male",
// "country": "UK"
// },
// "Sara": {
// "DOB": "13/05/1982",
// "gender": "female",
// "country": "FR"
// }
// }
// To swap an inner member:
JsonObject jsonSara = new JsonObject();
json.objectOf2("Sara", jsonSara);
index1 = jsonSara.indexOf("DOB");
index2 = jsonSara.indexOf("country");
jsonSara.swap(index1, index2);
// We now have this:
System.out.println(json.emit());
// {
// "petter": {
// "DOB": "26/02/1986",
// "gender": "male",
// "country": "US"
// },
// "Jon": {
// "DOB": "19/03/1984",
// "gender": "male",
// "country": "UK"
// },
// "Sara": {
// "country": "FR",
// "gender": "female",
// "DOB": "13/05/1982"
// }
// }
}
}