2017-06-13 157 views
0
{'countryName':USA,'countryCode':+41,'phoneNo':4427564321,'campaignId':111} 
{'countryName':USA,'countryCode':+41,'phoneNo':4427564321,'campaignId':111} 

现在我想将上面的JSON转换为映射到String的每个部分的POJO实例。假设POJO被称为userList。然后我需要将JSON字符串拆分为2 userListObjects需要帮助将json转换为pojo

+0

显示一些代码,你到目前为止尝试过。 –

回答

2

你的POJO类看起来像:

public class userList{ 

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

//Getters,Setters 

} 

您还可以使用this_link生成POJO只是通过复制和粘贴您的JSON。

+0

我认为他们希望以编程方式进行 –

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

     }