-1

Make a sample Java service which takes the following json from an endpoint as input, parses it and puts it into the database.

  1. Input: ​ The input will have a fixed format which will be posted as a content body to the endpoint.

  2. Output: ​ The output should be a number of rows that are filled in the database or error in case of failures.

Sample input :

   {
    "quiz": {
        "sport": {
              "q1": {
                  "question": "Which one is correct team name in NBA?",
                  "options": [
                        "New York Bulls",
                        "Los Angeles Kings",
                        "Golden State Warriros",
                        "Huston Rocket"
                        ],
                 "answer": "Huston Rocket"
                    }
                  },
         "maths": {
               "q1": {
                   "question": "5 + 7 = ?",
                   "options": [
                            "10",
                            "11",
                            "12",
                            "13"
                           ],
                    "answer": "12"
                     },
                "q2": {
                    "question": "12 - 8 = ?",
                    "options": [
                              "1",
                              "2",
                              "3",
                              "4"
                             ],
                     "answer": "4"
                      }
                   }
               }
          }

I've created a basic Rest service with springboot that takes in question, options and answer as input, and also displays it in the same way.

Ex. input :

   { 
     "question": "khis is the question part",
        "options": [
            "option 1",
            "option 2",
            "option 3",
            "option 4"
            ],
        "answer": "option 1"
       }

I have created a springboot project and created the following java classes: 1. QuestionSet.java

package com.example.demo.questionset;

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonRootName;



public class QuestionSet {

    private String question;
    private String options[];
    private String answer;


    public QuestionSet() {

    }




public QuestionSet(String question, String[] options, String answer) {
        super();
        this.question = question;
        this.options = options;
        this.answer = answer;
    }


    public String getQuestion() {
        return question;
    }
    public String[] getOptions() {
        return options;
    }
    public String getAnswer() {
        return answer;
    }
    public void setQuestion(String question) {
        this.question = question;
    }
    public void setOptions(String[] options) {
        this.options = options;
    }
    public void setAnswer(String answer) {
        this.answer = answer;
    }
    }

`

  1. QuestionSetService.java

    package com.example.demo.questionset;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Service;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.databind.ObjectWriter;
    
    
    @Service
    public class QuestionSetService {
    
    
    
    
    String nameString[] = {"kabir", "ram", "shyam", "varun"};
    
  2. QuestionSetController.java

package com.example.demo.questionset;

 import java.util.List;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.annotation.JsonGetter;

   @RestController
   public class QuestionSetController {

@Autowired
QuestionSetService questionSetService;


@RequestMapping("/questionsets")
public List<QuestionSet> getAllQuestionSets(){
    return questionSetService.getAllQuestionSets();
}

@RequestMapping("/questionsets/{question}")
public QuestionSet getQuestionSetByQuestion(@PathVariable String question)
 {
    return questionSetService.getQuestionSetByQuestion(question);
}

@PostMapping("/questionsets")
public void postController(
  @RequestBody QuestionSet questionSet) {

    questionSetService.addQuestionSet(questionSet);
}

  }





    private List<QuestionSet> questionSets = null;


    public List<QuestionSet> getAllQuestionSets() {
        return questionSets;
    }

    public QuestionSet getQuestionSetByQuestion(String question) {
        return questionSets.stream().filter(t ->             
    t.getQuestion().equals(question)).findFirst().get();
    }


    public ResponseEntity addQuestionSet( QuestionSet questionSet) {
        questionSets.add(questionSet);
        return ResponseEntity.ok(HttpStatus.OK);
    }

     }

I can take in simple json input in the form of questionset but the required json input is much more complex. I understand that I need to make wrapper classes and use objectmapper, but I don't know how.

halfer
  • 19,824
  • 17
  • 99
  • 186
Kabir Pathak
  • 41
  • 11
  • https://www.baeldung.com/jackson-deserialization You need to create custom deserializer. This answer should help you register custom deserializer once you create them. https://stackoverflow.com/questions/53480525/how-to-provide-a-custom-deserializer-with-jackson-and-spring-boot – Sneh Sep 11 '19 at 11:26
  • Thanks @Sneh. Can you please elaborate this a little more. I am new to SpringBoot and have to submit this project within the next 2 days. Can you please give me a solution that will be more specific to my problem? Or, can you give me a step by step approach as to what code I should write in order to get the desired result? Thanks a lot!!! – Kabir Pathak Sep 11 '19 at 11:33
  • As you wrote, just make pojo classes and declare the most outer pojo (with @ResponseBody annotation) as a parameter of controller method. – dgregory Sep 11 '19 at 12:03
  • @dgregory can you show me the code, as to how I can do this? Thanks for the help. – Kabir Pathak Sep 11 '19 at 19:51
  • wait, let me clear your problem. according to your comment in other answer, your json key name can be q1,q2 ..... q(n)? not just “question”:[]? and sport/math/blahblah? – dgregory Sep 12 '19 at 01:14
  • @drgregory yes you are correct! Thats the problem, the key can be q1,q2.. till q(n) and the subject can be anything, not just sports or maths! Can you please help me!!? I have to submit this project tomorrow anyhow! – Kabir Pathak Sep 12 '19 at 06:47
  • I think there is no elegant way to do that. As @Sneh 's comment, write your own deserializer or use [Map](https://www.baeldung.com/jackson-map) - it would be replaced with [ModelMap](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/ui/ModelMap.html). Will be mess but no choice but to. – dgregory Sep 13 '19 at 07:38
  • Could you give me the code that can perform this task? – Kabir Pathak Sep 14 '19 at 17:33

1 Answers1

0
            JSONObject obj = (JSONObject) parser.parse(reader);
            JSONObject response =(JSONObject) parser.parse(obj.get("quiz").toString());
            JSONObject sub =(JSONObject) parser.parse(response.get("sport").toString());
            JSONObject q1 = (JSONObject) parser.parse(sub.get("q1").toString());
            String question =(q1.get("question").toString());
            System.out.println(question);
            JSONArray options = (JSONArray)parser.parse(q1.get("options").toString());
            for(int i=0 ;i<options.size();i++) {
                System.out.println(options.get(i));
            }


Output :-
      Which one is correct team name in NBA?
      New York Bulls
      Los Angeles Kings
      Golden State Warriros
      Huston Rocket

This is a sample on how you can parse the input json using simple-json. Although there is a lot of manual work here, you can avoid it by using nested JSONArray and iterate over it.

Amol Gharpure
  • 129
  • 1
  • 7
  • The input will vary, and the tags like "sport" and "q1", "q2" will change, so I cannot parse them in this static way. – Kabir Pathak Sep 11 '19 at 20:22