We know in AEM 6.3, all JSON related operations are deprecated from package org.apache.commons.json.
For eg JSONParse, JSONObject.
Let us try to fix this using GSON. AEM has default GSON library to parse the JSON or for JSON processing & conversations.
How to convert a String to JsonObject using Gson library.
Below is the common syntax to use GSON in java code. To use this ensure your pom.xml has the GSON dependency added.
The pattern to use GSON is,
Gson gson = new Gson();
YourClass yourClassObject = new YourClass();
String jsonString = gson.toJson(yourClassObject);
Below given a real case example.
Say we have a multifield in AEM which has a JSON string array as,
String personalData = {"name": "Alex","age":"27","details": "User says at Washington"}
// Now we need to create a Java model class as given below. Remember to match the fields(keys in JSON with string variables )
public class PersonalData {
public String name;
public String age;
public String details;
}
//Now in our sling model or relevant class, the GSON invocation could be something like;
Gson gson = new Gson();
PersonalData persondata = gson.fromJson(personalData, PersonalData.class);
Another simple example is
Say we have a multifield as shown below.
String organization = {"org": "Google"}
// Our Java model class
public class OrgData {
public String org;
}
//invoking the method
Gson gson = new Gson();
OrgData orgdata = gson.fromJson(organization, OrgData.class);
Another example using JSON Element
package com.aem.core;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
//This class takes a json string and parse it to get its value from a key.
/*Say we have a json {"key":"value"}
Then to get its 'value' easily without using Java regular expression or patterns
We can use this approach
*/
public class MyJsonParser {
//You can run this code directly to test how it works
public static void main(String[] args) {
Gson gson = new Gson();
String jsonString = "{\"key\":\"value\"}";
//Create JSON element from JSON String
JsonElement element = gson.fromJson(jsonString, JsonElement.class);
//Fomr a Json Object from element
JsonObject jsonObject = element.getAsJsonObject();
//Below line takes the 'key' from json and print its 'value'
System.out.println(jsonObject.get("key").getAsString());
}
}
We can also use Jackson for JSON parsing in AEM.
No comments:
Post a Comment
If you have any doubts or questions, please let us know.