简体   繁体   中英

how to add dynamic value as object field name in java?

** Query**

@PostMapping("/students/create")
    public Student  postCandidate(@RequestBody Student  student) {

        Student  _student = repository.save(new Student  (student.getStudentname(), student.setRollno()));
        return _student;
    }

Code:

public class Student  {
    private String studentname;
    private int rollno;
    public Student(int rollno, String studentname) {
         this.rollno = rollno;
         this.studentname = studentname;
    }

    public String getStudentname() {
         return studentname;
    }
    public void setStudentname(String studentname) {
    this.studentname = studentname;
    }
    public int getRollno() {
    return rollno;
    }
    public void setRollno(int rollno) {
    this.rollno = rollno;
    }
}

Instead of getting rollno ="123" I want to get the dynamic data which I have passed: "ram"="123'

example:

{studentname:john, john:"123"},
{studentname:Ram, Ram:"124"}

You can use any JSON library to read the json data.

1) Read the value key studentname to get student name. 2) Read the value of key student's name from #1

Also, json provided in question is not valid. I have assumed the correct json would be

[
  {
    studentname: "john",
    john: "123"
  },
  {
    studentname: "Ram",
    Ram: "124"
  }
]

My attempt using GSON library:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class GsonTest {

    private static String json = "JSON STRING HERE";

    public static void main(String[] args) {
        Gson gson = new GsonBuilder().create();
        JsonElement jsonElement = gson.fromJson(json, JsonElement.class);
        JsonArray array = jsonElement.getAsJsonArray();
        Iterator<JsonElement> iterator = array.iterator();

        List<Student> students = new ArrayList<Student>();
        while (iterator.hasNext()) {
            JsonObject item = iterator.next().getAsJsonObject();
            // Roll No is read by reading dynamic key which is student name
            Student student = new Student(item.get(item.get("studentname").getAsString()).getAsInt(), item.get("studentname").getAsString());
            students.add(student);
        }
        students.forEach(item -> {
            System.out.println("Name : " + item.getStudentname() + " Roll No : " + item.getRollno());
        });
    }

}

Output:

Name : john Roll No : 123
Name : Ram Roll No : 124

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM