We didn't have to do anything special, we just call the toJson() method of Gson class and boom, you have your JSON document ready. There is a comma after every element as well. String values are properly enclosed within double quotes, while integer values had no wrapping. The json String will look like the following:Įven though String would not be as pretty-printed as this but just a single line, you can see that GSon has generated a properly formatted JSON document e.g. This will return the JSON String you are looking after. Next, we need to call the toJSon() function of Gson and pass the UserDetails object to this method. For now, let's just focus on serializing a simple Java object to JSON. The good thing is that you don't need to pass any parameter to create an instance of Gson class, but it doesn't mean that you cannot configure this object, of course, you can configure the Gson object to suit your need by enabling disabling various configuration parameters, which we'll learn in future articles. Let's create the object of Gson class for now: If you have never used any JSON parsing libraries in Java, then just remember, we need a class from the Gson library which will convert our Java object to JSON. UserDetails user = new UserDetails( order to serialize this object into equivalent JSON String, we need a Gson object, this is similar to ObjectMapper class of Jackson Databind library, in case you have used it before and trying Gson now. First of all, we need to create a Java object for this user So let's see how we can do the conversion with Gson. If we keep the field names the same, we would expect such a JSON or a normal user which doesn't own a credit card The task is now to convert this object to an equivalent JSON String which you can use it on your Android or Java application. It also has a boolean hasCreditCard field to indicate whether the user owns a credit card or not. If you look carefully, it got six attributes, out of those name, email, and the city is String objects, age is an integer that tells how old user is and the phone is a long value to accommodate both 8 digit and 10 digit numbers. Now, let's take a close look at this UserDetails class. Unlike many other frameworks, Gson also doesn't require a default, no-argument constructor. I have committed constructor, getters, and setter for simplicity. This is our simple POJO (Plain old Java object) which we will convert into JSON format. Let's see that class in action, it will look like following This method returns a valid JSON containing all fields as defined in the object. Call the Gson.toJSon(object) to convert the object into JSON String.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |