为什么Json对象在下面的Json值之前出现?

时间:2019-04-17 13:07:01

标签: java json

我正在尝试使用org.json.simple.JSONObject创建嵌套的json对象。为什么jsonobject更改顺序?

预期输出:

{  
  "id":"14",   
  "email":"xxx@gmail.com",    
  "Company":{   
    "address":"milton street",   
    "postal code":"cincinnati",   
    "name":"abc"  
  }  
}  

当前输出:

{  
"Company":{   
"address":"milton street",    
"postal code":"cincinnati",    
"name":"abc"  
},   
"id":"14",   
"email":"xxx@gmail.com"  
} 

这是我的代码:

 JSONObject First = new JSONObject();
    First.put("id", "14");
    First.put("email", "xxx@gmail.com");

    JSONObject companydetails = new JSONObject();
    companydetails.put("name", "abc");
    companydetails.put("address", "milton street");
    companydetails.put("postal code", "cincinnati");

    First.put("Company",companydetails);

    System.out.println(First.toString());

4 个答案:

答案 0 :(得分:1)

使用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 download

答案 1 :(得分:1)

在此处查看答案:JSON order mixed up

您不能也不应该依赖JSON对象中元素的顺序。

摘自http://www.json.org/的JSON规范:

“对象是名称/值对的无序集合”

因此,JSON库可以自由地按其认为合适的方式重新排列元素的顺序。这不是错误。

答案 2 :(得分:0)

JsonObject不会保持顺序,也没关系,因为您将通过键访问json。

答案 3 :(得分:0)

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