Expand my Community achievements bar.

SOLVED

How to Split JSONArray

Avatar

Level 4

Hi All,

 

I have customized CF model, as shown below.

 

subnaik_0-1687422525294.png

 

 

NOTE - My location Name value is coming from database

 

I have written the JSON and in JSON my location name is coming like below.

************* JSON **************

"testLocations":
{"City":[{"id":"161341","name":"Badarganj"}],
"Country":[{"id":"157031","name":"India"}]}

 

I have written below java to get my testlocations JSON

 

************** JAVA Needs To Update*************

 

 

 

 

 

 

private void settestLocations(Resource masterResource, Node masterNode,
			testPublishModel testModel) throws RepositoryException {
		
		LOGGER.info("Inside  locations");
		JsonObject testLocations = new JsonObject();
		ValueMap masterResourceValueMap = masterResource.getValueMap();
		if(masterNode.hasProperty(Constants.test_LOCATIONS)) {
			String[] testLocationsStringArray = masterResourceValueMap.get(Constants.test_LOCATIONS, String[].class);
			for (String testLocationString : testLocationsStringArray) {
				JsonObject testLocation = gson.fromJson(testLocationString, JsonObject.class);				
				String locationType = StringUtils.EMPTY;
				JsonArray locationName = new JsonArray();
				if (testLocation.has(LOCATION_TYPE)) {
					locationType = testLocation.get(LOCATION_TYPE).getAsString();
				}
				
				if (testLocation.has(LOCATION_NAME)) {
					locationName = testLocation.get(LOCATION_NAME).getAsJsonArray();
					LOGGER.info("locationName12345 ==== " + locationName);
				}
				testLocations.add(locationType, locationName);
			}
		}
		testModel.settestLocations(testLocations);
	}

 

 

 

 

 

 

********************* testmodel JAVA class is as below ********************

 

 

 

 

 

import java.util.List;

import com.google.gson.JsonObject;


public class TestModel {

	JsonObject testLocations;
	
	List<testLocationsEntity> locationName;

	
	public JsonObject gettestLocations() {
		return testLocations;
	}

	public void settestLocations(JsonObject testLocations) {
		this.testLocations = testLocations;
	}
	
	
	public List<testLocationsEntity> gettestLocationName() {
		return locationName;
	}

	public void settestLocationName(List<testLocationsEntity> testLocationNameList) {
		this.locationName = testLocationNameList;
	}

	

	@Override
	public String toString() {
		return "TestModel [ testLocations=" + testLocations 
				+ ", locationName123=" + locationName + "]";
	}

}

 

 

 

 

 

 

Here requirement is that my JSON should come like below , as highlighted in Red

"testLocations":{
"City":[{"id":"161341","testName[Badarganj]"}],
"Country":[{"id":"161341","testName[India]"}]
}

 

I tried lots of option but still not able to achieve the required JSON .

 

Thanks in advance

Subrat

1 Accepted Solution

Avatar

Correct answer by
Level 4

Dear all,

My issue is resolved. Just adding below line of code in bold

 

testLocationString = testLocationString .replace("name", "communityName");

 

for (String testLocationString : testLocationsStringArray) {
testLocationString  = testLocationString .replace("name", "communityName");
				JsonObject testLocation = gson.fromJson(testLocationString, JsonObject.class);

 

View solution in original post

5 Replies

Avatar

Community Advisor

Hello @subnaik  - 

 

You can use a JSON library such as Jackson for this purpose : 

 

 

//Imports
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

//Code
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(originalJson);
            transformJsonNode(rootNode);
            String transformedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
            System.out.println(transformedJson);
        } catch (Exception e) {
            e.printStackTrace();
        }

    private static void transformJsonNode(JsonNode node) {
        if (node.isObject()) {
            ObjectNode objectNode = (ObjectNode) node;
            objectNode.fields().forEachRemaining(entry -> transformJsonNode(entry.getValue()));
        } else if (node.isArray()) {
            for (JsonNode childNode : node) {
                transformJsonNode(childNode);
            }
        } else if (node.isValueNode() && node.isTextual()) {
            String value = node.asText();
            ((ObjectNode) node).put(0, "testName[" + value + "]");
        }

 

 

Regards,

Tanika 

Avatar

Level 4

Hi @Tanika02  and all

 

I changes in my Java class, as shown below , but it is coming error , as shown below

 

subnaik_1-1687431482363.png

 

Also I am not sure why you put system.out.println as in AEM it is not working.

private void settestLocations(Resource masterResource, Node masterNode, CommunityPublishModel testModel) throws RepositoryException {
		
		LOGGER.info("Inside  locations");
		JsonObject testLocations = new JsonObject();
		ValueMap masterResourceValueMap = masterResource.getValueMap();
		if(masterNode.hasProperty(Constants.COMMUNITY_LOCATIONS)) {
			String[] testLocationsStringArray = masterResourceValueMap.get(Constants.COMMUNITY_LOCATIONS, String[].class);
			for (String testLocationString : testLocationsStringArray) {
				JsonObject testLocation = gson.fromJson(testLocationString, JsonObject.class);				
				String locationType = StringUtils.EMPTY;
				JsonArray locationName = new JsonArray();
				if (testLocation.has(LOCATION_TYPE)) {
					locationType = testLocation.get(LOCATION_TYPE).getAsString();
				}
				if (testLocation.has(LOCATION_NAME)) {
					locationName = testLocation.get(LOCATION_NAME).getAsJsonArray();
					LOGGER.info("locationName12345 ==== " + locationName);
				}
				testLocations.add(locationType, locationName);
			}
		}
		testModel.setCommunityLocations(testLocations);
	            ObjectMapper objectMapper = new ObjectMapper();
	            JsonNode rootNode = objectMapper.readTree(testLocations);
	            transformJsonNode(rootNode);
	            String transformedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
	            LOGGER.info("transformedJson ==== "+transformedJson);
	}
	
	private static void transformJsonNode(JsonNode node) {
	        if (node.isObject()) {
	            ObjectNode objectNode = (ObjectNode) node;
	            objectNode.fields().forEachRemaining(entry -> transformJsonNode(entry.getValue()));
	        } 
	        else if (node.isArray()) {
	            for (JsonNode childNode : node) {
	                transformJsonNode(childNode);
	            }
	        } 
	        else if (node.isValueNode() && node.isTextual()) {
	            String value = node.asText();
	            ((ObjectNode) node).put("testName[" + value + "]", 0);
	        }
	 }
	

 

Avatar

Community Advisor

Hello @subnaik - 

 

The above code block was just for your reference. Please remove the unnecessary piece.

 

Do you have the right imports?

 

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

 

If Not, Please add.

 

Additionally, make sure you have the required Jackson dependencies in your project's build configuration.

Avatar

Level 4

Hi Tanika,

 

Yes I have all imports . But I think you are not clear with my requirement. let me tell you once again.

 

I need to change only name to communityName marked as bold, like here. can we use something like replace "or" anything else rather than so much code.

 

if (communityLocation.has(LOCATION_NAME)) {
locationName = communityLocation.get(LOCATION_NAME).getAsJsonArray(); // Currently locationName is coming like [{"id":"157031","name":"India"}]
LOGGER.info("locationName12345 ==== " + locationName);
}

Avatar

Correct answer by
Level 4

Dear all,

My issue is resolved. Just adding below line of code in bold

 

testLocationString = testLocationString .replace("name", "communityName");

 

for (String testLocationString : testLocationsStringArray) {
testLocationString  = testLocationString .replace("name", "communityName");
				JsonObject testLocation = gson.fromJson(testLocationString, JsonObject.class);