4 回答
TA贡献1812条经验 获得超5个赞
使用 google/gson 库
JsonObject o=new JsonObject();
o.addProperty("id", "14");
o.addProperty("email", "xxx@gmail.com");
JsonObject companydetails1 = new JsonObject();
companydetails1.addProperty("name", "abc");
companydetails1.addProperty("address", "milton street");
companydetails1.addProperty("postal code", "cincinnati");
o.add("Company",companydetails1);
System.out.println(o.toString());
使用 Maven 回购
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
或者用外部jar下载
TA贡献2036条经验 获得超8个赞
在此处查看答案:JSON 顺序混淆
您不能也不应该依赖 JSON 对象中元素的顺序。
来自http://www.json.org/的 JSON 规范:
“对象是一组无序的名称/值对”
因此,JSON 库可以根据需要自由地重新排列元素的顺序。这不是错误。
TA贡献2041条经验 获得超4个赞
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.Builder;
import lombok.Getter;
import org.junit.Test;
public class TestJUnit {
@Test
public void exec() {
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String toPrint = gson.toJson(ToJsonFormat.builder()
.id(14)
.email("xxx@gmail.com")
.company(Company.builder()
.address("milton street")
.postCode("cincinnati")
.name("abc")
.build())
.build());
System.out.println(toPrint);
}
@Getter
@Builder
private static class ToJsonFormat {
private int id;
private String email;
private Company company;
}
@Getter
@Builder
private static class Company {
private String address;
@JsonProperty("post code")
private String postCode;
private String name;
}
}
结果:
{"id":14,"email":"xxx@gmail.com","company":{"address":"milton street","post_code":"cincinnati","name":"abc"}}
添加回答
举报