【问题标题】:JSON Input for POST request to call REST API用于调用 REST API 的 POST 请求的 JSON 输入
【发布时间】:2020-02-04 15:28:42
【问题描述】:

如何转换模型 Person 以匹配输入?

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

(字符串中的名称,int 中的年龄和 double 中的 amountInBank)

我希望我的 JSON 输入如下:

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

目前我调用 REST API 的代码是:

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);

尝试了很多方法,但无法实现 JSON 格式列表的预期输入。请帮忙

方法一:

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

方法二:

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

方法三:

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);

【问题讨论】:

    标签: java json api clientresource


    【解决方案1】:

    首先您必须创建 JSONObject 并输入 ID H123。 然后你必须创建另一个 JSONObject 将接受一个人的详细信息。 将另一个 JSONObject 传递给 JSONArray 并将路径 JSONArray 传递给 JSONObjct。检查代码

     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();
        }
    

    }

    上面的代码会产生输出

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

    }

    如果您需要从数据库中执行此操作,则更像会有很多人。将 person 对象和 json 对象放入某种循环中,并根据需要填充它。然后将其传递给 json 数组和 json 数组到 jsonobject 以获得许多记录。

    【讨论】:

      【解决方案2】:

      试试下面的代码

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

      邮政数据

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

      【讨论】:

      • 您能否解释一下代码的作用以及它为什么有用?仅代码答案被标记为低工作量。我们都在这里学习,StackOverflow 不仅仅是解决手头问题的工具。谢谢。
      • 根据他的问题,他想将JSON对象作为参数传递,这就是为什么我刚刚放了如何创建JSON对象请求对象的代码
      【解决方案3】:

      最安全的选择是使用知名库进行编组,例如Jackson。它能够将您的对象转换为 JSON 格式,如下所示:

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

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

      还有其他选择,这只是个人喜好,因为 Jackson 被广泛使用且有据可查。

      如果您尝试获取数组 JSON 对象的列表,那么只需将 Person 对象替换为 List&lt;Person&gt; 并尝试对其进行编组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-15
        • 2016-12-03
        • 2018-12-16
        • 1970-01-01
        • 2019-12-14
        • 2018-01-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多