Friday 24 May 2019

How to fix JSON deprecated API error in AEM? Alternatives of Deprecated JSON API in AEM

When ever we need to retrieve a value from JSON using its key, JSONParser is a better and easy approach.

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;


//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'

We can also use Jackson for JSON parsing in AEM.

More Like This:

AEM 6.5 Site related new features

AEM 6.5 Specific new features in Assets section

New Features in AEM 6.5 Forms

Foundation updates in AEM 6.5 which a developer should be aware of

Cloud Manager for AEM 6.5 New features

Storage concepts in AEM 6.5   

HTML Template language updates which needs to be observed with AEM 6.5

No comments:

Post a Comment