Converting object to json Android/Java

Tram Ho

Converting your Object to json is very easy by using JSONObject or other json libraries. Here is an example of using the JSONObject to convert a model class (Student) into json below

Here we have a basic model with properties such as id, name and so on. If we were to convert this to json we can create a method toJSON to convert this Object.

Now to test we can simply create a student model and log or toast the converted json on the device.


Converted Json >>>: {"id":1,"gender":"Male","age":22,"first_name":"Pane","last_name":"Detroit","address":"No 2 sw lane detroit"}

That’s it! Happy Coding.

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo