0

basically taking in a json object via a post api thats like the following

{
    [
        param_name: "name", 
        param_value: "jason"
        param_type: "varchar"
    ],
    [ 
        param_name: "age", 
        param_value: "15"
        param_type: "varchar"
    ]
}

then i want to convert it to a predefined java object where the parameter names are the same as the "param_value" values.

Is there anyway to do this in java, with a method like this?

student.setparamname(object.get("param_name"),object.get("param_value") );
sorifiend
  • 5,927
  • 1
  • 28
  • 45
  • Yes there are plenty of ways, but it entirely depends on which json library you use, and which methods it has avaliable. – sorifiend Apr 08 '22 at 05:40
  • 1
    Does this answer your question? [How to parse JSON in Java](https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) and see the [Javadoc](https://docs.oracle.com/javame/8.0/api/json/api/com/oracle/json/JsonObject.html) `JSONArray array = jsonObject.getJSONArray("");` and `String name = array.getJsonObject(0).getString("param_name");` – sorifiend Apr 08 '22 at 05:47

1 Answers1

0

You would want something like this if my interpretation of your question is correct. This allows you to POST to the endpoint with an object and specify name and age in json format. I'm going to say that the above is a Student for example but that's just an example object. If you want to include validation have a look at using @Valid. What you've declared in the question is a JsonArray (indicated by the [] after the {}) within a JsonObject but there is no need for that, just create the JsonObject with the fields you require.

@JsonDeserialize(builder = NewStudent.Builder.class)
    public class NewStudent{
    private String name;
    private String age;
    //getters and setters here
    //create builder here
    }

   public class Student{
private String name;
private String age;
//getters and setters here
}


@PostMapping(value = "/addstudent", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Student> createStudent(@RequestBody NewStudent newStudent){
Student student = new Student();
student.setName(newStudent.getName());
student.setAge(newStudent.getAge());
ResponseEntity<Student> responseContent = ResponseEntity.body(student);
return responseContent;

}

  • this isnt really what im asking, the input isnt a student object json, its just a list of param values and parameter values, and i want to create a populate a student object whose variable names = the param name values exactly from the json exactly. – javaUser Apr 08 '22 at 06:15