需要帮助将json转换为pojo

时间:2017-06-13 09:05:49

标签: java json pojo

Server.withRouter() {
  case GET(p"/repositories") => Action {
    Results.Ok(Json.arr(Json.obj("full_name" -> "octocat/Hello-World")))
  }
} { implicit port => ...

现在我想将上面的{'countryName':USA,'countryCode':+41,'phoneNo':4427564321,'campaignId':111} {'countryName':USA,'countryCode':+41,'phoneNo':4427564321,'campaignId':111} 转换为映射到String的每个部分的POJO实例。假设POJO被称为JSON。然后我需要将userList字符串拆分为2 JSON

2 个答案:

答案 0 :(得分:2)

您的Pojo课程将如下所示:

public class userList{

 private String countryName;
 private String countryCode;
 private Long phoneNo;
 private Integer campaignId;

 //Getters,Setters

}

您也可以使用this_link通过复制和粘贴json来生成pojo。

答案 1 :(得分:0)

使用以下代码段生成列表。

    JsonParser jsonParser = new JsonParser();
    String jsonData = "[{\"countryName\":\"USA\",\"countryCode\":\"+41\",\"phoneNo\":4427564321,\"campaignId\":111},{\"countryName\":\"USA\",\"countryCode\":\"+41\",\"phoneNo\":4427564321,\"campaignId\":111}]";
    JsonElement parsedJsonElement = jsonParser.parse(jsonData);
    if(parsedJsonElement.isJsonArray()){
        JsonArray parsedJsonArray =  parsedJsonElement.getAsJsonArray();
        List<User> userList = new ArrayList<User>();
        for(JsonElement jsonElement : parsedJsonArray){
            String countryName = "";
            String countryCode = "";
            long phoneNo = 0;
            int campaignId = 0;
            Iterator<Entry<String, JsonElement>> iterator = jsonElement.getAsJsonObject().entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, JsonElement> next = iterator.next();
                String key = next.getKey();
                if(key.equals("countryName")){
                    countryName = next.getValue().getAsString();
                }else if(key.equals("countryCode")){
                    countryCode = next.getValue().getAsString();
                }else if(key.equals("phoneNo")){
                    phoneNo = next.getValue().getAsLong();
                }else if(key.equals("campaignId")){
                    phoneNo = next.getValue().getAsInt();
                }
            }
            userList.add(new User(countryName, countryCode, phoneNo, campaignId));
        }
    }


        public class User {
            String countryName;
            String countryCode;
            long phoneNo;
            int campaignId;
            public User(String countryName, String countryCode, long phoneNo, int campaignId) {
                super();
                this.countryName = countryName;
                this.countryCode = countryCode;
                this.phoneNo = phoneNo;
                this.campaignId = campaignId;
            }

        }