Search code examples
javajsonrequestput

how can i create a json using javaobject.?


how can i create a json using javaobject. ? I did it, but I'm getting an error.

I need to build a body to parse within the PUT request. If anyone can help me.

public static String generateJSON(String status, String assignee, String comment,String data, String filename, String contentType) throws IOException {

          JSONArray jsonArray = new JSONArray();

          JSONObject statusObj = new JSONObject();
          statusObj.put("status", status);
          statusObj.put("comment", comment); 
          statusObj.put("assignee", assignee); 
          statusObj.put("comment", comment);
          
          JSONObject evidenceObj = new JSONObject();
          evidenceObj.put("evidence", "newXML");
          evidenceObj.put("data", data);
          evidenceObj.put("filename", filename);
          evidenceObj.put("contentType", contentType);

          // Add the objects to the jsonArray
          jsonArray.add(evidenceObj);
          
          // Add the key tests jsonObject to the jsonArray
          evidenceObj.put("add", jsonArray);

          String jsonString = evidenceObj.toString();
          
          return jsonString;
       } 

Solution

  • Why not just to create your own Class with needed fields, and then use jackson library to convert it to JSON string, use method writeValueAsString().

    Example:

    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public static void main(String[] args) throws Exception
    {
        Example exObject = new Example();
        exObject.setField1("data");
        exObject.setField2("second data");
        exObject.setField3(72);
    
        System.out.println(new ObjectMapper().writeValueAsString(exObject));
    }
    

    Log console:

    Output:
    {
      "field1" : "data",
      "field2" : "second data",
      "field3" : 72
    }
    

    Example class is:

    private static class Example
    {
        private String field1;
        private String field2;
        private int field3;
    
        public String getField1()
        {
            return field1;
        }
    
        public void setField1(String field1)
        {
            this.field1 = field1;
        }
    
        public String getField2()
        {
            return field2;
        }
    
        public void setField2(String field2)
        {
            this.field2 = field2;
        }
    
        public int getField3()
        {
            return field3;
        }
    
        public void setField3(int field3)
        {
            this.field3 = field3;
        }
    }
    

    Note: Example class must have getter + setter methods for all fields