Convert the Model class or List into JSON string.

Sometimes making the json structure is so hard, but this way could be very easier to do any kind of object model into json structure.


Add the following dependency in app.gradle.
compile 'com.google.code.gson:gson:2.5'


Example:
User.Java
public class User {
    String userId;
    String userName;
    String userAge;
    String userAddress;
    String userCity;

    public User() {
    }

    public User(String userId, String userName, String userAge, String userAddress, String userCity) {
        this.userId = userId;
        this.userName = userName;
        this.userAge = userAge;
        this.userAddress = userAddress;
        this.userCity = userCity;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserAge() {
        return userAge;
    }

    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }

    public String getUserAddress() {
        return userAddress;
    }

    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }

    public String getUserCity() {
        return userCity;
    }

    public void setUserCity(String userCity) {
        this.userCity = userCity;
    }
}

And your activity or any place:
List<User> list = new ArrayList<>();
list.add(new User("001", "Ashton", "19", "South Street", "London"));
list.add(new User("002", "Alex", "20", "East 2nd Street", "London"));
list.add(new User("003", "Ann", "18", "East 3rd Street", "London"));

System.out.println(new Gson().toJson(list));

Result:

[
  {
    "userAddress": "South Street",
    "userAge": "19",
    "userCity": "London",
    "userId": "001",
    "userName": "Ashton"
  },
  {
    "userAddress": "East 2nd Street",
    "userAge": "20",
    "userCity": "London",
    "userId": "002",
    "userName": "Alex"
  },
  {
    "userAddress": "East 3rd Street",
    "userAge": "18",
    "userCity": "London",
    "userId": "003",
    "userName": "Ann"
  }
]

You can do with any kind list, object or even hashmap or hashtable to convert to json string. Wish you happy new year 2018. Have a happy sunday friends..


Comments

Popular posts from this blog

Clear the app data programmatically in android

convert an integer to a string in java

Print the large string values in android log cat.