first of all, my question would be a bit long but i dont think its complex. But i simply have not clue where the problem could be.
So let me start.
Im trying to print an Arraylist into webpages. I have a json file like this:
[
{
"id": 0,
"brand": "audi",
"model": "q8",
"color": "red",
"price": "123",
"available": false
},
{
"id": 1,
"brand": "audi",
"model": "r6",
"color": "sfg",
"price": "952",
"available": true
},
{
"id": 2,
"brand": "BMW",
"model": "IDK",
"color": "Red",
"price": "105",
"available": true
}
]
I read the json file and save the data into an arraylist "carList" with this method
try(JsonReader jsonReader = new JsonReader(new InputStreamReader(new FileInputStream(this.db)))){
Gson myGson = new Gson();
JsonParser jsonParser = new JsonParser();
JsonArray array = jsonParser.parse(jsonReader).getAsJsonArray();
this.carList = new ArrayList<Car>();
for (JsonElement element : array) {
Car car = myGson.fromJson(element, Car.class);
carList.add(car);
}
}catch(IOException e){
e.printStackTrace();
}
My "Car" class has those variables
private int id = 0;
private String brand;
private String model;
private String color;
private String price;
private boolean available = true;
And when i print my "carList" with this
public ArrayList<Car> printAllCars(){
return carList;
}
and this
#RequestMapping(value = "/cars", method = RequestMethod.GET)
#ResponseBody
ArrayList<Car> printAllCars() {
return cars.printAllCars();
}
I got this with postman
postman result
So as you can see, the problem is the price is not printed and "available" is printed as "state".
But when i print in eclipse the price is displayed.
eclipse result
Sorry for my long post, my bad english and my bad code but please help me guys !
Jackson looks at get...() and set...() methods, so don't forget to add these methods or us filed-based serialization.
Related
I am new to GeoJSON and im currently running into an issue that I just don't know how to do it.
Here is a snippet of what my FeatureCollection looks like
FeatureCollection fc = new FeatureCollection();
Map<String, Object> properties = new HashMap<String, Object>();
for(int i = 0; i < platforms.size(); i ++) {
Feature feature = new Feature();
Point geometry = new Point();
Dto dto = platforms.get(i);
Position position = new Position(dto.getLat(), dto.getLon());
fc.addFeature(feature);
geometry.setCoordinates(position);
feature.setGeometry(geometry);
feature.setProperties(properties);
properties.put("name", dto.getName());
properties.put("msl", dto.getMsl());
properties.put("id", dto.getId());
}
return fc.toString();
I want my output to look like this:
{
"type":"FeatureCollection"
features":[
{
"type":"Feature"
"geometry": {
"type":"Point"
"coordinates":[
-120.200000,
10.100000
]
},
"properties": {
"name": "1"
"height": "100.00"
"id": "null"
}
}
{
"type":"Feature"
"geometry": {
"type":"Point"
"coordinates\":[
-130.200000,
20.100000
] \n "
}, \n "
"properties": { "
"name": "2"
"height": "100.00"
"id": "null"
}
}
]
}
As far as I can tell, through debugging, the correct information is being placed into the feature but whenever I return the featureCollection I get this:
mil.nga.sf.geojson.FeatureCollection#366ac49b
I don't know much about geojson but it seems like I'm incorrectly returning the FeatureCollection and its printing out its name or whatever.
Simply put, how do I print the contents of a FeatureCollection?
EDIT:
This is the output that I get after implementing gson.
{
"features": [
{
"feature": {
"geometry": {
"x": 10.1,
"y": -120.2,
"z": null,
"m": null,
"geometryType": "POINT",
"hasZ": false,
"hasM": false
},
"properties": {
"msl": 100.0,
"name": "1",
"id": null
}
},
"id": null,
"bbox": null,
"foreignMembers": {}
},
{
"feature": {
"geometry": {
"x": 20.1,
"y": -130.2,
"z": null,
"m": null,
"geometryType": "POINT",
"hasZ": false,
"hasM": false
},
"properties": {
"msl": 100.0,
"name": "2",
"id": null
}
},
"id": null,
"bbox": null,
"foreignMembers": {}
}
],
"bbox": null,
"foreignMembers": {}
I am unsure what to do moving forward to get this to mirror my desired output.
Your problem is that you're calling fc.toString();, which will hit the default Object.toString() method. This will dump some classname+address/id-like String, depending on th JVM used.
Instead of calling toString(), you should use a JSON library like google gson, and add
a few lines to the bottom of your code:
final GsonBuilder gb = new GsonBuilder();
gb.setPrettyPrinting();
gb.serializeNulls();
// gb.excludeFieldsWithoutExposeAnnotation(); // maybe use for more control
final Gson gson = gb.create();
final String jsonText = gson.toJson(fc);
return jsonText;
Also consider writing a utility class that does this for you with default settings that you choose:
public class MyJsonUtil {
static public String toJSON(final Object pObject) {
final GsonBuilder gb = new GsonBuilder();
gb.setPrettyPrinting();
gb.serializeNulls();
// gb.excludeFieldsWithoutExposeAnnotation(); // maybe use for more control
final Gson gson = gb.create();
final String jsonText = gson.toJson(pObject);
return jsonText;
}
}
and then at the end of your code you simply call return MyJsonUtil.toJSON(fc).
Before you assume that this question is a duplicate based on its title, I must say that I couldn't find any solutions out there for my specific problem. However, I'd appreciate it if you could suggest some links! That said, my problem is that I keep getting the following GSON exception:
07-24 10:12:44.713 2540-2603/com.davenotdavid.dndheadlines W/System.err: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
I understand that I'm somehow passing in a JSON object as opposed to an array, but what I don't understand is how it's not working based on the following Utility class that basically has helper methods to parse and extract JSON data from a JSON array using the OkHttpClient and GSON libraries, and then returns a list of extracted data back to the calling class:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class QueryUtils {
public static List<Article> fetchArticleData(String requestUrl) {
String jsonResponse = "";
try {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(requestUrl)
.build();
Response response = okHttpClient.newCall(request).execute();
jsonResponse = response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
return extractDataFromJson(jsonResponse);
}
private static List<Article> extractDataFromJson(String jsonResponse) {
if (jsonResponse == null || jsonResponse.isEmpty()) {
return null;
}
List<Article> articlesList = new ArrayList<>();
ArticleResponse[] articleResult = new ArticleResponse[0];
try {
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<ArticleResponse>>(){}.getType();
// *** Exception is thrown here ***
Collection<ArticleResponse> enums = gson.fromJson(jsonResponse, collectionType);
articleResult = enums.toArray(new ArticleResponse[enums.size()]);
} catch (Exception e) {
e.printStackTrace();
}
if (articleResult.length != 0) {
for (int i = 0; i < articleResult.length; i++) {
ArticleResponse article = articleResult[i];
articlesList.add(new Article(
article.getTitle(),
article.getUrl(),
article.getUrlToImage(),
article.getPublishedAt()));
}
}
return articlesList;
}
}
As you'll notice that the exception is thrown in the following line of code:
Collection<ArticleResponse> enums = gson.fromJson(jsonResponse, collectionType);
Here's the ArticleResponse class I generated using GsonFormat:
public class ArticleResponse {
/**
* author : Annalee Newitz
* title : First glimpse of Steven Spielberg’s new movie, Ready Player One
* description : This trailer introduces us to a VR dystopia, and has the greatest soundtrack ever.
* url : https://arstechnica.com/the-multiverse/2017/07/first-glimpse-of-steven-spielbergs-new-movie-ready-player-one/
* urlToImage : https://cdn.arstechnica.net/wp-content/uploads/2017/07/RPO-1000x437-nbv413pszkz7s29g3blop7i6ymcv84f9mtwmvt1xxk-760x380.png
* publishedAt : 2017-07-23T17:13:56Z
*/
private String title;
private String url;
private String urlToImage;
private String publishedAt;
public String getTitle() {
return title;
}
public void setTitle(String title) {this.title = title;}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
}
A sample JSON response from a network call in the Utility class is as follows:
{
"status": "ok",
"source": "ars-technica",
"sortBy": "top",
"articles": [{
"author": "Eric Berger",
"title": "Elon Musk’s Mars rocket may be about to lose half of its engines",
"description": "Downscaling the Mars booster suggests that Musk may be bending toward reality.",
"url": "https://arstechnica.com/science/2017/07/elon-musk-drops-an-important-hint-about-his-revised-mars-rocket/",
"urlToImage": "https://cdn.arstechnica.net/wp-content/uploads/2017/07/29937260386_45ba70fb85_h-1440x614-760x380.jpg",
"publishedAt": "2017-07-24T13:12:01Z"
}, {
"author": null,
"title": "Hour of Devastation review: The evil elder dragon god-pharaoh has arrived. RIP.",
"description": "Plus, a look at the major changes coming to future Magic: the Gathering sets.",
"url": "https://arstechnica.com/gaming/2017/07/magic-hour-of-devastation-review/",
"urlToImage": "https://cdn.arstechnica.net/wp-content/uploads/2017/07/401538_CN-copy-760x380.jpg",
"publishedAt": "2017-07-24T13:00:52Z"
}, {
"author": "Annalee Newitz",
"title": "Season 2 of Stranger Things looks even creepier and more intense",
"description": "The Upside Down is back, and it looks like it's about to eat the world.",
"url": "https://arstechnica.com/the-multiverse/2017/07/season-2-of-stranger-things-looks-even-creepier-and-more-intense/",
"urlToImage": "https://cdn.arstechnica.net/wp-content/uploads/2017/07/landscape-1486986380-stranger-things-mike-wheeler-2-760x380.jpg",
"publishedAt": "2017-07-23T23:20:39Z"
}, {
"author": "Annalee Newitz",
"title": "First glimpse of Steven Spielberg’s new movie, Ready Player One",
"description": "This trailer introduces us to a VR dystopia, and has the greatest soundtrack ever.",
"url": "https://arstechnica.com/the-multiverse/2017/07/first-glimpse-of-steven-spielbergs-new-movie-ready-player-one/",
"urlToImage": "https://cdn.arstechnica.net/wp-content/uploads/2017/07/RPO-1000x437-nbv413pszkz7s29g3blop7i6ymcv84f9mtwmvt1xxk-760x380.png",
"publishedAt": "2017-07-23T17:13:56Z"
}, {
"author": null,
"title": "New book explores how protesters—and governments—use Internet tactics",
"description": "The protest frontiers are changing. An entrenched researcher explains why they work.",
"url": "https://arstechnica.com/tech-policy/2017/07/twitter-and-tear-gas-book-explores-new-world-of-digital-protest/",
"urlToImage": "https://cdn.arstechnica.net/wp-content/uploads/2017/07/Screen-Shot-2017-07-22-at-1.17.15-PM-760x380.png",
"publishedAt": "2017-07-23T15:00:02Z"
}, {
"author": "Nathan Mattise",
"title": "Maybe The Americans is quietly a technophile love letter to the 1980s",
"description": "Joel Fields and Joe Weisberg talk handheld football, spy tech, mail robot, and more.",
"url": "https://arstechnica.com/the-multiverse/2017/07/maybe-the-americans-is-quietly-a-technophile-love-letter-to-the-1980s/",
"urlToImage": "https://cdn.arstechnica.net/wp-content/uploads/2017/07/AmericansFootball-600x380.jpg",
"publishedAt": "2017-07-23T14:30:15Z"
}, {
"author": "Sam Machkovech",
"title": "Dockless bike sharing lands in Seattle—and leads us down unsavory alleyways",
"description": "Now in Seattle: two services, 1,000 bikes, and a shoulder shrug at helmet laws.",
"url": "https://arstechnica.com/business/2017/07/dockless-bike-sharing-lands-in-seattle-and-leads-us-down-unsavory-alleyways/",
"urlToImage": "https://cdn.arstechnica.net/wp-content/uploads/2017/07/IMAG3645-760x380.jpg",
"publishedAt": "2017-07-23T14:00:32Z"
}, {
"author": null,
"title": "Level up: How video games evolved to solve significant scientific problems",
"description": "Science, your chance to use all that time spent gaming for the greater good.",
"url": "https://arstechnica.com/gaming/2017/07/level-up-how-video-games-evolved-to-solve-significant-scientific-problems/",
"urlToImage": "https://cdn.arstechnica.net/wp-content/uploads/2017/07/GettyImages-134429675-760x380.jpg",
"publishedAt": "2017-07-23T13:25:25Z"
}, {
"author": "John Timmer",
"title": "We’ve screwed up the coasts so badly that an invasive species is a plus",
"description": "When native species are gone, an invasive one can provide ecosystem services.",
"url": "https://arstechnica.com/science/2017/07/weve-screwed-up-the-coasts-so-badly-that-an-invasive-species-is-a-plus/",
"urlToImage": "https://cdn.arstechnica.net/wp-content/uploads/2017/07/Gracilaria-vermiculophylla-760x380.jpg",
"publishedAt": "2017-07-23T12:00:53Z"
}, {
"author": "Megan Geuss",
"title": "German energy company wants to build flow batteries in old natural gas caverns",
"description": "Research for a massive redox flow battery is underway.",
"url": "https://arstechnica.com/business/2017/07/german-energy-company-wants-to-build-flow-batteries-in-old-natural-gas-caverns/",
"urlToImage": "https://cdn.arstechnica.net/wp-content/uploads/2017/07/20170612-b4p-english-760x380.jpg",
"publishedAt": "2017-07-22T15:00:22Z"
}]
}
You cannot convert your jsonObject in an Array you must have a jsonArray to do this. Simply add this lines:
JsonObject jsonObject = gson.fromJson(jsonResponse, JsonObject.class);
String articlesArrayResponse = jsonObject.getAsJsonArray("articles").getAsString();
before your exception happens. Obviously you must change the argument in that line for this:
Collection<ArticleResponse> enums = gson.fromJson(articlesArrayResponse, collectionType);
I hope it helps you!
The reason why you are getting this error is because your json response begins with a json object and you are telling json to parse the articles response which is an array.
{
"status": "ok",
"source": "ars-technica",
"sortBy": "top",
"articles": [{
"author": "Eric Berger",
"title": "Elon Musk’s Mars rocket may be about to lose half of its engines",
"description": "Downscaling the Mars booster suggests that Musk may be bending toward reality.",
"url": "https://arstechnica.com/science/2017/07/elon-musk-drops-an-important-hint-about-his-revised-mars-rocket/",
"urlToImage": "https://cdn.arstechnica.net/wp-content/uploads/2017/07/29937260386_45ba70fb85_h-1440x614-760x380.jpg",
"publishedAt": "2017-07-24T13:12:01Z"
},
....
}]
}
So in order to do that, you need to first retrieve the articles json array and then pass it to gson.fromJson() method. You can do that by doing some change in fetchArticleData() method -
public static List<Article> fetchArticleData(String requestUrl) {
String jsonResponse = "";
try {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(requestUrl)
.build();
Response response = okHttpClient.newCall(request).execute();
jsonResponse = response.body().string();
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray articleArray = jsonObject.getJSONArray("articles");
return extractDataFromJson(articleArray.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I am new to GSON. I need to convert the following JSON response into a List.
JSON response:
{
"data": [{
"data": {
"ac_id": "000",
"user_id": "000",
"title": "AAA"
}
}, {
"data": {
"ac_id": "000",
"user_id": "000",
"title": "AAA"
}
}]
}
I have a class to cast data
Account. java
public class Account {
public int ac_id;
public int user_id;
public String title;
#Override
public String toString(){
return "Account{"+
"ac_id="+ac_id+
", user_id="+user_id+
", title="+title+'}';
}
}
When I cast the response with my class I get:
[Account{ac_id="000", user_id="000", title="AAA"}, Account{ac_id="000", user_id="000", title="AAA"}]
Now I need to put these two values into a List<Account>.
What do you suggest?
JSONObject data = new JSONObject(response);
JSONArray accounts = data.getJSONArray("data");
List<Account> accountList = new Gson().fromJson(accounts.toString(), new TypeToken<ArrayList<Account>>(){}.getType());
If you cannot change your JSON response to remove the inner "data" key, you can use this:
Gson gson = new Gson();
ArrayList<Account> accountList = new ArrayList<Account>();
JSONArray accounts = data.getJSONArray("data");
for (int i = 0; i < accounts.length(); i++) {
JSONObject a = accounts.getJSONObject(i).getJSONObject("data");
accountList.add(gson.fromJson(a.toString(), Account.class));
}
For that you can use Tokens so that gson can understand the custom type...
TypeToken<List<Account>> token = new TypeToken<List<Account>>(){};
List<Account > accountList= gson.fromJson(response, token.getType());
for(Account account : accountList) {
//some code here for looping }
That nested "data" key is pointless. If you can fix your JSON you should make this instead.
{
"data": [{
"ac_id": "000",
"user_id": "000",
"title": "AAA"
}, {
"ac_id": "000",
"user_id": "000",
"title": "AAA"
}]
}
And then this will work.
JSONObject data = new JSONObject(response);
JSONArray accounts = data.getJSONArray("data");
List<Account> accountList = new Gson()
.fromJson(accounts.toString(), new TypeToken<ArrayList<Account>>(){}.getType());
Or, again, that first "data" isn't really necessary either.
If you can get your JSON just to be the list of Accounts...
[{
"ac_id": "000",
"user_id": "000",
"title": "AAA"
}, {
"ac_id": "000",
"user_id": "000",
"title": "AAA"
}]
This will work
List<Account> accountList = new Gson()
.fromJson(response, new TypeToken<ArrayList<Account>>(){}.getType());
if you have access to where the JSON was created, i think you should make it like this:
{"data":[{"ac_id":"000","user_id":"000","title":"AAA"},{"ac_id":"000","user_id":"000","title":"AAA"}]}
then to convert it, just use this code: (where jsonString is the string above)
List<Account> accountList = new Gson().fromJson(jsonString, new TypeToken<ArrayList<Account>>(){}.getType());
I have an end-point which returns me this response:
{
"head": {
"status": 200,
"ok": true,
"messages": [],
"errors": [],
"references": {}
},
"body": {
"id": "d57a9c7aef9842c2e31a0f49c",
"flowId": "f57979d06f9842c3e94f1f197",
"creationDate": 1470744494732,
"path": "/luafanti/test",
"version": 0,
"elems": {
"xxx": {
"type": "integer",
"value": 200
}
}
}
}
My question is, how to make a model that can be populated with only a part of my json response. For example, with this:
"xxx": {
"type": "integer",
"value": 200
}
or this:
"elems": {
"xxx": {
"type": "integer",
"value": 200
}
}
Using Jackson, you can define your model as the following:
#JsonIgnoreProperties(ignoreUnknown=true)
public class MyResponseModel {
private Body body;
public void setBody(Body body) {this.body = body;}
public Body getBody() {return body;}
#JsonIgnoreProperties(ignoreUnknown=true)
public static class Body {
private Elems elems;
// getter and setter for elems
}
#JsonIgnoreProperties(ignoreUnknown=true)
public static class Elems {
private Xxx xxx;
// getter and setter for xxx
}
#JsonIgnoreProperties(ignoreUnknown=true)
public static class Xxx {
private String type;
private String value;
// getter and setter for type and value
}
}
The above is quite verbose, particularly if you are only interested in a very small part of the response. It may be more practical to handle the response as a String and then use e.g. JsonPath to extract only the data you are interested in.
You can use simple-json.jar to extract that object from inside the JSONObject
Downloadable Jar Link - simple-json.jar Download Link
Maven Jar Import Maven Repository pom syntax
You actual object is
{
"head": {
"status": 200,
"ok": true,
"messages": [],
"errors": [],
"references": {}
},
"body": {
"id": "d57a9c7aef9842c2e31a0f49c",
"flowId": "f57979d06f9842c3e94f1f197",
"creationDate": 1470744494732,
"path": "/luafanti/test",
"version": 0,
"elems": {
"xxx": {
"type": "integer",
"value": 200
}
}
}
} // hold this complete object in any string reference Variable.
Here I Suppose String jsonString holds the complete json object as above described.
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.JSONObject;
// implemetation logic for extracting jsonObject.
private JSONObject extractFirstBlock(String jsonString) throws ......{
JSONObject jsonObj ;
JSONParser parser=new JSONParser(); // parser to parse string to JSONObject
jsonObj = (JSONObject) parser.parse(jsonString); // parse the Object using parse Method.
String desiredObject = (String) jsonObj.get("body"); // this Object contains your desired output which you wish to receive.
jsonObj = parser.parse(desiredObject);
desiredObject = jsonObj.get("elems"); // you will get your desired object as you expected.
}
Here in desiredObject you will get your expected Values as JSONObject.
"xxx": {
"type": "integer",
"value": 200
}
Below is the json object structure which I want to create.
{
"userInfo": {
"email": "a#a.com",
"full_name": "Niraj Rajbhandari",
"password": "buddhanagar",
"business_category_id": "0",
"user_type": "0"
},
"businessAddress": {
"street1": "Shram Marg",
"state": "Bagmati",
"zip": "0234",
"phone1": "3458364853",
"country": "nepal"
},
"companyInfo": {
"name": "Test",
"vat_date": "2015-05-06",
"vat_status": "0",
"registration_number": "1"
}
}
Below are the my codes.
public class RegistrationModel {
public List<UserInfo> userInfo;
public List<BusinessModel> businessAddress;
public List<CompanyInfoModel> companyInfo;
}
public class Tax
{
Gson gson = new Gson();
RegistrationModel registrationModel = new RegistrationModel();
// User list data
registrationModel.userInfo = new ArrayList<UserInfo>();
UserInfo userInfo = new UserInfo();
userInfo.setEmail(personinfo.get(0).getEmail());
userInfo.setFull_name(personinfo.get(0).getFull_name());
userInfo.setPassword(personinfo.get(0).getPassword());
userInfo.setBusiness_category_id(personinfo.get(0).getBusiness_category_id());
userInfo.setUser_type(personinfo.get(0).getUser_type());
registrationModel.userInfo.add(userInfo);
// Business Address
registrationModel.businessAddress = new ArrayList<BusinessModel>();
BusinessModel businessModel = new BusinessModel();
businessModel.setStreet1(businessModels.get(0).getStreet1());
businessModel.setState(businessModels.get(0).getState());
businessModel.setZip(businessModels.get(0).getZip());
businessModel.setPhone1(businessModels.get(0).getPhone1());
businessModel.setCountry(businessModels.get(0).getCountry());
registrationModel.businessAddress.add(businessModel);
// Company Data
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
//get current date time with Date()
Date date = new Date();
registrationModel.companyInfo = new ArrayList<CompanyInfoModel>();
CompanyInfoModel companyInfoModel = new CompanyInfoModel();
companyInfoModel.setName(businessModels.get(0).getCompany_Name());
companyInfoModel.setVat_date(dateFormat.format(date));
companyInfoModel.setVat_status(0);
companyInfoModel.setRegistration_number(Hmrc_reg_no.getText().toString());
registrationModel.companyInfo.add(companyInfoModel);
gson.toJson(registrationModel)
}
the above code generate the below structure
{
"userInfo": [{
"email": "a#a.com",
"full_name": "Niraj Rajbhandari",
"password": "buddhanagar",
"business_category_id": "0",
"user_type": "0"
}],
"companyInfo": [{
"name": "Test",
"vat_date": "2015-05-06",
"vat_status": "0",
"registration_number": "1"
}],"businessAddress": [{
"street1": "Shram Marg",
"state": "Bagmati",
"zip": "0234",
"phone1": "3458364853",
"country": "nepal"
}]
}
Can anyone please give me a code to create the json object strucure in JAVA. In the above code I don't want []bracket . I want the above mention structure
use this code:
JSONObject o1=new JSONObject("userInfo");
o1.put("email","a#a.com");
o1.put(...);
JSONObject o2=new JSONObject("businessAddress");
o2.put("street1","shram Marg");
o2.put(...);
JSONObject o3=new JSONObject("companyInfo");
o3.put("name","Test");
o3.put(...);
JSONArray array=new JSONArray();
array.put(o1);
array.put(o2);
array.put(o3);
change your RegistrationModel to this
public class RegistrationModel {
public UserInfo userInfo;
public BusinessModel businessAddress;
public CompanyInfoModel companyInfo;
}
and then
registrationModel.userInfo = new UserInfo(); //remove this line
.....
your code
.....
registrationModel.userInfo=userInfo;
and same for rest 2 objects also