JSON Input for POST request to call REST API

无人久伴 提交于 2019-12-24 19:48:00

问题


How do i convert a model Person to match the input?

Person p = new Person(name, age, amountInBank);

(name in String, age in int and amountInBank in double)

I want my JSON Input to be as follow:

{  
 "ID": "H123",
 "list" : [
      {
       "name" : "ally",
        "age": 18,
         "amountInBank": 200.55
       }
  ]
}

Currently my code to call REST API is:

JSONObject jsonInput= new JSONObject();
jsonInput.put("ID", "H123");

 //put in list input in JSON -> HELP NEEDED    

Resource resource = client.resource(URL HERE);

resource.contentType(MediaType.APPLICATION_JSON);
resource.accept(MediaType.APPLICATION_JSON);

ClientResponse cliResponse = resource.post(jsonInput);

Tried many ways but couldn't achieve the expected input for list in JSON format. Please help

Method 1:

ArrayList<Map<String, Object>> list = new ArrayList<>();
list.add(p);
jsonInput.put("list" , list);

Method 2:

JSONArray jsonArr = new JSONArray();
jsonArr.add(p);
jsonInput.put("list", jsonArr);    

Method 3:

Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "ally");
map.put("age", 18);
map.put("amountInBank" : 255.55);
jsonInput.put("list", map);

回答1:


Safest bet is to use a well known library for the marshalling, such as Jackson. It is able to convert your object to JSON format with the following:

ObjectMapper mapper = new ObjectMapper(); //from Jackson library
Person p = new Person(name, age, amountInBank); //your POJO
String jsonString = mapper.writeValueAsString(p); //convert

Source: https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

There are also other alternatives, this is just a personal preference as Jackson is very widely used and well documented.

If you're trying to get a list of array JSON objects then just substitute the Person object with List<Person> and try to marshall that.




回答2:


Try the code below

val listJsonArry = JsonArray()

var jsonObject = JsonObject()
jsonObject.add("name", "ally")
jsonObject.add("age", "18")
jsonObject.add("amountInBank", "200.55")

listJsonArry.add(jsonObject)   

PostData

var postjsonObject = JsonObject()
postjsonObject.add("ID", "H123")
postjsonObject.add("list", listJsonArry)



回答3:


First you have to create JSONObject and put ID, H123. Then you have to create Another JSONObject wich will accept a person details. pass another JSONObject to JSONArray and path JSONArray to JSONObjct. check the code

 public static void main(String[] args) {

    JSONObject jsonObject = new JSONObject(); // first json object
    jsonObject.put("ID", "H123"); put ids.

    JSONArray jsonArray = new JSONArray(); // prepear json array

    Person person = new Person("Ally", 18, 200.55); // create person object and populate it with data

   // JSONObject jsonObject = new JSONObject(person); you can pass your person directly to JSONObject constructor and it will deparse it base on your getter methods in person class. 

    JSONObject jsonObject1 = new JSONObject(); // then pass person data to Json object
    jsonObject1.put("name", person.getName());
    jsonObject1.put("age", person.getAge());
    jsonObject1.put("amountInBank", person.getAmountInBank());

    jsonArray.put(jsonObject1); // pass json object to json array

    jsonObject.put("list", jsonArray); // and pass json array to json object

    System.out.println();
    try (FileWriter file = new FileWriter("person.json")) {

        file.write(jsonObject.toString(5));
        file.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }

}

above code will produce output

{
 "ID": "H123",
 "list": [{
      "name": "Ally",
      "amountInBank": 200.55,
      "age":  18
 }]

}

if you need to do that from database, more like there will be a lot of persons. put person object and json object in some kind of loop and populate it as long as you want. then pass it to json array and json array to jsonobject to have many records.



来源:https://stackoverflow.com/questions/58267787/json-input-for-post-request-to-call-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!