如何在Java中制作json对象

时间:2018-06-20 15:35:47

标签: java json

我需要将以下JSON对象发送到API之一。谁能告诉我如何使用org.json lib将其转换为JAVA中的JSON对象。

{ “ hostHeaderInfo”: {“ sourceCode”:“ xxx”, “ requestId”:“ xxx”, “ requestToken”:“ xxx”, “ requestType”:“ xxx”, “ affiliateCode”:“ xx”, “ sourceChannelId”:“ xxx” }

“数字”:“ xxxx”, “ first”:“ xx”, “第二”:“ xx” }

1 个答案:

答案 0 :(得分:0)

在Java中,我们有杰克逊绑定JSON API,可将Java转换为JSON,并将JSON转换为Java。

Java的JSON字符串:

JSON:

String data = "{ "hostHeaderInfo": {"sourceCode": "xxx", "requestId": "xxx", "requestToken": "xxx", "requestType": "xxx", "affiliateCode": "xx", "sourceChannelId": "xxx" }, "number":"xxxx", "first":"xx", "second":"xx" }"; 

JavaObject obj = new ObjectMapper().readValue(data, JavaObject.class);

Java对象转换为JSON:

JavaObject obj = ;  //Java class object reference here
String data = new ObjectMapper().writeValueAsString(obj);

注意:这里JavaObject可以是将根据JSON要求进行字段设置的任何类