There is "\" when converting JSONObject to String

1. Before modification

DwxxDTO dwxxDTO = new DwxxDTO();
dwxxDTO.setEntname("测试公司");
dwxxDTO.setUniscid("91110100000000000Y");
dwxxDTO.setOrgancode("MA0000000");

ZgcbdjDTO zgcbdjDTO = new ZgcbdjDTO();
zgcbdjDTO.setCpdata(dwxxDTO);
zgcbdjDTO.setType(type);
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(zgcbdjDTO);

//方式一
Map<String, String> body = new HashMap<String, String>();
body.put("sha1", zaiyao);
body.put("data", jsonObject.toString());
String bodyStr = JSONObject.toJSONString(body);
//方式一打印结果
{
    
    
  "sha1": "tdvbaaaaaaaaA=",
  "data": "{\"type\":\"2\",\"cpdata\":{\"uniscid\":\"91110100000000000Y\",\"entname\":\"测试公司\",\"organcode\":\"MA0000000\"}}"
}

//方式二
JSONObject body = new JSONObject();
body.put("sha1", zaiyao);
body.put("data", jsonObject.toString());
String bodyStr = JSONObject.toJSONString(body);
//方式二打印结果
{
    
    
  "sha1": "tdvbaaaaaaaaA=",
  "data": "{\"type\":\"2\",\"cpdata\":{\"uniscid\":\"91110100000000000Y\",\"entname\":\"测试公司\",\"organcode\":\"MA0000000\"}}"
}

2. Reason:

It may be because jsonboject contains another json string. You should extract the json string inside and put it into jsonobject using the fluenPut(key, value) method;

3. After modification

DwxxDTO dwxxDTO = new DwxxDTO();
dwxxDTO.setEntname("测试公司");
dwxxDTO.setUniscid("91110100000000000Y");
dwxxDTO.setOrgancode("MA0000000");

ZgcbdjDTO zgcbdjDTO = new ZgcbdjDTO();
zgcbdjDTO.setCpdata(dwxxDTO);
zgcbdjDTO.setType(type);
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(zgcbdjDTO);

JSONObject body = new JSONObject();
body.fluentPut("sha1",zaiyao);
body.fluentPut("data",jsonObject);
System.out.println("body入参:" + bodyStr);
//打印结果
{
    
    
  "sha1": "tdvbaaaaaaaaA=",
  "data": {
    
    
    "type": "2",
    "cpdata": {
    
    
      "uniscid": "91110100000000000Y",
      "entname": "测试公司",
      "organcode": "MA0000000"
    }
  }
}

4. fluentPut source code:

public JSONObject fluentPut(String key, Object value) {
    
    
        map.put(key, value);
        return this;
 }

Guess you like

Origin blog.csdn.net/m0_46459413/article/details/126054627#comments_25491740