How to create the below JSON Object Structure in Java - java

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

Related

Returning a GeoJSON object in java

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).

The structure of my GeoJSON does not allow LeafLet to display the points on the layer

I am using the leaflet-ajax project (https://github.com/calvinmetcalf/leaflet-ajax) and I want to declare a geojsonLayer variable like this :
var geojsonLayer = L.geoJson.ajax("http://localhost:7070/findInArea");
where http://localhost:7070/findInArea is an endpoint to a Dropwizard REST web service that I coded.
Before trying to use http://localhost:7070/findInArea as a parameter I tried as parameter a JSON file containing what my REST web service returns :
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"imo": 0,
"course": "0.0",
"description": "description",
"mmsi": 432473000,
"type": "VESSEL",
"heading": "NaN"
},
"geometry": {
"type": "Point",
"coordinates": [-4.064533333333333, 5.29355]
}
}, {
"type": "Feature",
"properties": {
"imo": 0,
"course": "0.0",
"description": "description",
"mmsi": 375488000,
"type": "VESSEL",
"heading": "NaN"
},
"geometry": {
"type": "Point",
"coordinates": [-4.025521666666666, 5.303138333333333]
}
}, {
"type": "Feature",
"properties": {
"imo": 0,
"course": "0.0",
"description": "description",
"mmsi": 355794000,
"type": "VESSEL",
"heading": "NaN"
},
"geometry": {
"type": "Point",
"coordinates": [-4.01319, 5.28968]
}
}]
}
When I try with this JSON the points are not displayed on the layer. I searched on the Web an example of (Geo)JSON for which it works. On https://github.com/calvinmetcalf/leaflet-ajax/tree/gh-pages/example I found one which is :
{
"type":"FeatureCollection",
"features":[
{
"geometry":{
"type":"Point",
"coordinates":[
-71.123723098996251,
42.379003083976961
]
},
"type":"Feature",
"id":0,
"properties":{
"UNDERGRAD":43,
"CITYST":"Cambridge, MA",
"OBJECTID":72.0,
"URL":"http://www.longy.edu",
"TYPE":"PRI",
"DESCRIPTN":"4-year or above",
"NCES_ID":"166489",
"ZIPCODE":"02138",
"L_ACC_EST":16,
"SITE":"1",
"L_SRC_1":"nces.ed.gov",
"L_BASE":"DOQ",
"DEGREES":"C, M",
"L_TYPE":"CB",
"ADDRESS":"One Follen St",
"COLLEGE":"Longy School Of Music",
"L_METH":"IN-WEBSITE",
"GRAD":137,
"MAIN_TEL":"(617) 876-0956"
}
},
{
"geometry":{
"type":"Point",
"coordinates":[
-71.308156671517793,
42.643612284195882
]
},
"type":"Feature",
"id":1,
"properties":{
"UNDERGRAD":79,
"CITYST":"Lowell, MA",
"OBJECTID":73.0,
"URL":"http://www.lowellacademy.com",
"TYPE":"PRI",
"DESCRIPTN":"less-than-2-year",
"NCES_ID":"166498",
"ZIPCODE":"01852",
"L_ACC_EST":16,
"SITE":"1",
"L_SRC_1":"nces.ed.gov",
"L_BASE":"DOQ",
"DEGREES":"C",
"L_TYPE":"CB",
"ADDRESS":"136 Central St",
"COLLEGE":"Lowell Academy Of Hairdressing",
"L_METH":"IN-VERB",
"GRAD":0,
"MAIN_TEL":"(978) 453-3235"
}
}
]
}
Currently the Java code of my REST web service is :
#Override
public FeatureCollection findTracksInACertainArea(double longitudeMin, double longitudeMax, double latitudeMin, double latitudeMax){
FeatureCollection fc = new FeatureCollection();
List<Feature> features = new ArrayList<Feature>();
DBCursor cursor = null;
BasicDBObject query = new BasicDBObject();
query.put("detection.position.0", BasicDBObjectBuilder.start("$gte", longitudeMin).add("$lte", longitudeMax).get());
query.put("detection.position.1", BasicDBObjectBuilder.start("$gte", latitudeMin).add("$lte", latitudeMax).get());
cursor = collection.find(query);
while(cursor.hasNext()) {
final Track track = TrackDAOHelper.convertTrackFromDBObject(cursor.next());
features.add(buildFeature(track));
}
fc.setFeatures(features);
return fc;
}
private Feature buildFeature(Track track) {
Feature feature = new Feature();
Point point = new Point(track.getDetection().getPosition().getLongitude(), track.getDetection().getPosition().getLatitude());
feature.setGeometry(point);
Map<String, Object> properties = buildProperties(track);
feature.setProperties(properties);
return feature;
}
private Map<String, Object> buildProperties(Track track) {
Map<String, Object> properties = new HashMap<String, Object>();
if (track != null) {
if (track.getName() != null)
properties.put("name", track.getName());
properties.put("course", "0.0");
properties.put("heading", "NaN");
properties.put("type", "VESSEL");
if (track.getMmsi() != null)
properties.put("mmsi", track.getMmsi());
if (track.getImo() != null)
properties.put("imo", track.getImo());
if (track.getCallsign() != null)
properties.put("callsign", track.getCallsign());
String description = buildDescription();
properties.put("description", description);
}
return properties;
}
private String buildDescription() {
return "description";
}
How can I modify it in order to get a working (Geo)JSON?
It is not due to the JSON, it is due to the around Javascript code

Convert JSON response into List<T>

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());

Print an Arraylist to RESTful webservices

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.

How to get json value using GSON from json tree

I have a json such as below
{
"apiVersion": "v1",
"metadata": {
"status": {
"statusCode": 0
},
},
"stuff": [
{
"name": {
"text": "red"
},
"properties": [
{
"attributes": {
"shade": "dark"
},
"component": {
"id": "BA1",
}
"type": "Color"
}
]
},
{
"name": {
"text": "Toyota Camry"
},
"properties": [
{
"attributes": {},
"component": {
"id": "MS",
},
"type": "Vehicle"
}
]
},
]
}
I'm using GSON to parse the results like this:
Gson gson = new Gson();
JsonObject json = (JsonObject) gson.fromJson(in, JsonObject.class);
System.out.println(json.get("apiVersion").getAsString());
I can get the apiVersion but don't know how to get elements that are inside the json tree. For example, type...what if I want to output all the different type..in this case Color and Vehicle
I must be missing something here, but why can't you nest calls to getJsonObject? For example, to get the status code:
System.out.println(json.getAsJsonObject("metadata")
.getAsJsonObject("status")
.get("statusCode").getAsInt());
You can create an object in that matter and to parse the json to it (with GSON):
ParsedObject parsedObject = new Gson().fromJson(json, ParsedObject.class);
public class ParsedObject {
#SerializedName(value = "apiVersion")
private String mApiVersion;
#SerializedName(value = "metadata")
private Metadata mMetadata;
}

Categories

Resources