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

Maintenant, je veux convertir le JSON ci-dessus dans mes instances de POJO qui correspond à chaque partie de la chaîne. Supposons que le POJO soit appelé userList. Ensuite, je dois diviser la chaîne JSON en 2 userListObjects.Besoin d'aide pour convertir JSON POJO

+0

Montrez du code que vous avez essayé jusqu'à présent. –

Répondre

2

Votre classe POJO ressemblera:

public class userList{ 

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

//Getters,Setters 

} 

Vous pouvez également utiliser this_link pour générer POJO simplement en copiant et collant votre JSON.

+0

Je pense qu'ils veulent le faire par programme –

0

Utilisez l'extrait ci-dessous pour générer la liste.

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

     }