如何使用javaobject创建json?

fafcakar  于 2021-08-25  发布在  Java
关注(0)|答案(3)|浏览(512)

如何使用javaobject创建json?我做到了,但我犯了个错误。
我需要在put请求中构建一个要解析的主体。如果有人能帮我。

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;
       }
knsnq2tg

knsnq2tg1#

为什么不创建自己的带有所需字段的类,然后使用 jackson 要将其转换为json字符串,请使用 writeValueAsString() .
例子:

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

日志控制台:

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

示例类是:

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

注意:对于所有字段,示例类必须具有getter+setter方法

des4xlb0

des4xlb02#

jsonArray.add(evidenceObj);
// ...
evidenceObj.put("add", jsonArray);

你不能那样做,有一个循环依赖。如果java不能防止这种行为,那么当您导出json时,就会出现无限循环或堆栈溢出

fcy6dtqo

fcy6dtqo3#

感谢您的回复@adir d。。。我在我的代码中应用了它,但是我在实现数组和代码的对象示例时遇到了一些问题:

public static String exampleJSON(String fileName) throws JsonProcessingException {
         //Convert the file to base64
         File file = new File(Setup.xmlPath+fileName);
         String data = encodeFileToBase64(file);

        // create `ObjectMapper` instance   
         ObjectMapper mapper = new ObjectMapper();

         //Create a object and set the information that will be sent to update the test
         UpdateFieldsJSON fields = new UpdateFieldsJSON();

        //Define map which will be converted to JSON
         UploadEvidence[] evidence = Stream.of(
          new UploadEvidence("data", fileName,"plain/text"))
           .toArray(UploadEvidence[]::new);

         fields.setStatus(fields.getStatus());
         fields.setComment(fields.getComment());
         fields.setAssignee("");
         fields.setAdd(evidence);
         fields.setEvidences("{"); // I need to create the object and insert the array

        //Convert Object to JSON
         String objecToJSon = mapper.writeValueAsString(fields);

         return objecToJSon;

     }

   This is the output of my code...
  {
    "status": "PASS",
    "comment": "...",
    "assignee": "Miranda Bruno",
    "evidences": null,
    "add": [{
        "data": "data",
        "filename": "1.1newSpot.xml",
        "contentType": "plain/text"
    }]
}

我需要的是:

{
    "status": "PASS",
    "comment": "comment about the test",
    "assignee": "admin",
    "evidences": {
        "add": [{
            "data": "base64",
            "filename": "example.txt",
            "contentType": "plain/text"
        }]
    }
}

相关问题