Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

SOLVED

Return servlet response as json data.

Avatar

Level 2

I'm working on servlet registered on path & wanted to return its content in json data.
Currently, my servlet is fetching data from 

"/content/myproject/language-masters/en/jcr:content/root/container/container/componentname". Here values in component are injected via model & same used for servlet. I'm referring this blog. This is my code:
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
try {
ResourceResolver resourceResolver = request.getResourceResolver();

Resource resource = resourceResolver.getResource("/content/myproject/language-masters/en/jcr:content/root/container/container/mycomponent");

ProductDetails model = resource.adaptTo(ProductDetails.class);

response.getWriter().print("Product Specs are =>\n\nProduct Name: " + model.getName() + "\nPhone Ram: " + model.getRam() + "\nLaptop OS: " + model.getOs() + "\nTV Screensize: "+ model.getSize() + "\nWatch Dial Shape: " + model.getShape() + "\nProduct Prices: "+ model.getPrice());

resourceResolver.close();
} catch

and its working good, displaying text. 

But for current requirement, I want to return this as json data(need necessary not to be in key:value pair, just json data anyway) in response. So, please tell me how can I do this?

1 Accepted Solution

Avatar

Correct answer by
Level 6

You can use google.gson api to pass json in response. try this.

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {

ResourceResolver resourceResolver = request.getResourceResolver();

Resource resource = resourceResolver.getResource("/content/myproject/language-masters/en/jcr:content/root/container/container/mycomponent");

ProductDetails productDetails = ProductDetails.builder().id("component-id").name("modelname").build();

String jsonString = this.gson.toJson(productDetails);


PrintWriter out = response.getWriter();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        out.print(jsonString);
        out.flush();
}
import lombok.Builder;
import lombok.Data;

import java.io.Serializable;

@Builder
@Data
public class ProductDetails implements Serializable {
    private int id;
    private String name;
}

If you don't want to use lombok then use entity class like this

public class ProductDetails {
	private String id;
        private String name;
    //Getters/Setters
    }

and ProductDetails product = new ProductDetails("component-id", "model name");

String jsonString = this.gson.toJson(product);

 

View solution in original post

9 Replies

Avatar

Level 3

Hi @sesmic ,

 

You can do it by jackson or Gson parsing. You will get many examples over internet about the process.

Avatar

Level 2

Thanks for replying. Sorry, but I don't know how to use them. Can you give some hint please?

 

Avatar

Level 2

Thanks for the reply.
I can't understand about how can I adapt it to my code.

 

Avatar

Employee

@sesmic Here is another simple example which you can follow [1], this example uses gson.

public class EmployeeServlet extends HttpServlet {

    private Gson gson = new Gson();

    @Override
    protected void doGet(
      HttpServletRequest request, 
      HttpServletResponse response) throws IOException {
        Employee employee = new Employee(1, "Emp name", "IT", 5000);
        String employeeJsonString = this.gson.toJson(employee);

        PrintWriter out = response.getWriter();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        out.print(employeeJsonString);
        out.flush();   
    }
}

[1] https://www.baeldung.com/servlet-json-response

Avatar

Community Advisor

Hi @sesmic,

 

As suggested by @Mohit_KBansal, you can get your data in JSON, but are you using servlet just for that?
I would recommend using Sling Exporters to have your data in an easier way.

 

check this: https://experienceleague.adobe.com/docs/experience-manager-learn/foundation/development/develop-slin... 

 

Thanks,

Sravan

Avatar

Level 2

Thanks all! I imported com.google.gson.Gson and added values to json (String myJsonString = this.gson.toJson(model);) then object out.print(myJsonString).

 

Avatar

Correct answer by
Level 6

You can use google.gson api to pass json in response. try this.

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {

ResourceResolver resourceResolver = request.getResourceResolver();

Resource resource = resourceResolver.getResource("/content/myproject/language-masters/en/jcr:content/root/container/container/mycomponent");

ProductDetails productDetails = ProductDetails.builder().id("component-id").name("modelname").build();

String jsonString = this.gson.toJson(productDetails);


PrintWriter out = response.getWriter();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        out.print(jsonString);
        out.flush();
}
import lombok.Builder;
import lombok.Data;

import java.io.Serializable;

@Builder
@Data
public class ProductDetails implements Serializable {
    private int id;
    private String name;
}

If you don't want to use lombok then use entity class like this

public class ProductDetails {
	private String id;
        private String name;
    //Getters/Setters
    }

and ProductDetails product = new ProductDetails("component-id", "model name");

String jsonString = this.gson.toJson(product);