Grouping JSON output by an attribute - java

I have a source JSON string I would like to convert into local-attributed JSON. I'm trying to achieve:
{
"dep": 1552928400000,
"des": "USA",
"listWagonDetail": [
{
"listSeatDetail": [
{
"seatColumn": "A",
"seatRow": "1",
"seatStatus": "1",
"subclass": "C"
},
{
"seatColumn": "A",
"seatRow": "2",
"seatStatus": "0",
"subclass": "C"
},
{
"seatColumn": "A",
"seatRow": "3",
"seatStatus": "1",
"subclass": "C"
}
],
"numSeat": 0,
"wagonCode": "PRE",
"wagonNo": "1"
},
{
"listSeatDetail": [
{
"seatColumn": "A",
"seatRow": "1",
"seatStatus": "0",
"subclass": "C"
},
{
"seatColumn": "A",
"seatRow": "2",
"seatStatus": "0",
"subclass": "C"
},
{
"seatColumn": "A",
"seatRow": "3",
"seatStatus": "1",
"subclass": "C"
}
],
"numSeat": 0,
"wagonCode": "PRE",
"wagonNo": "2"
}
],
"numWagon": 0,
"org": "AU",
"subClass": null,
"trainNo": "77"
}
Which is to group each listSeatDetail by WagonNo. But instead I got this on my work where "numSeat", "wagonCode" and "WagonNo" is looped every listSeatDetail and only the last data of each array are shown:
{
"dep": 1552928400000,
"des": "USA",
"listWagonDetail": [
{
"listSeatDetail": [
{
"seatColumn": "A",
"seatRow": "3",
"seatStatus": "1",
"subclass": "C"
}
],
"numSeat": 0,
"wagonCode": "PRE",
"wagonNo": "2"
},
{
"listSeatDetail": [
{
"seatColumn": "A",
"seatRow": "3",
"seatStatus": "1",
"subclass": "C"
}
],
"numSeat": 0,
"wagonCode": "PRE",
"wagonNo": "2"
},
{
"listSeatDetail": [
{
"seatColumn": "A",
"seatRow": "3",
"seatStatus": "1",
"subclass": "C"
}
],
"numSeat": 0,
"wagonCode": "PRE",
"wagonNo": "2"
},
How can I achieve the first JSON? Here is part of my code:
private void generateSeat(GetSeatRequest request, GetSeatMapResponse seatMapResponse,
SeatMapResponsePojo seatmapResponsePojo) {
seatMapResponse.setDepDate(request.getDepDate());
seatMapResponse.setDes(request.getDes());
seatMapResponse.setOrg(request.getOrg());
seatMapResponse.setTrainNo(request.getTrainNo());
seatMapResponse.setNumWagon(0);
seatMapResponse.setSubClass(request.getSubClass());
List<WagonDetail> listWagonDetail = new ArrayList<>();
for (SeatMapPojo seatmap : seatmapResponsePojo.getPayload()) {
WagonDetail wagon = new WagonDetail();
String wagonNoString = seatmap.getStamformdetcode();
String[] wagonNo = wagonNoString.split("-");
for (WagonDetail wagondetail : listWagonDetail) {
wagondetail.setNumSeat(0);
wagondetail.setWagonCode(wagonNo[0]);
wagondetail.setWagonNo(wagonNo[1]);
List<SeatDetail> listSeatDetail = new ArrayList<>();
SeatDetail seatDetail = new SeatDetail();
seatDetail.setSeatColumn(seatmap.getWagondetcol());
seatDetail.setSeatRow(seatmap.getWagondetrow());
seatDetail.setSeatStatus(seatmap.isIsavilable() ? "0" : "1");
seatDetail.setSubclass(seatmap.getSubclass());
listSeatDetail.add(seatDetail);
wagondetail.setListSeatDetail(listSeatDetail);
}
listWagonDetail.add(wagon);
}
seatMapResponse.setListWagonDetail(listWagonDetail);
}

I'd recommend you to use google Gson, which is the best serialize/deserialize Library of JSON so far we found.
which you could define the desired class like this:
class Output{
private int depDate;
private String des;
...
private List<WagonDetail> listWagonDetail;
//... getter()/setter()
}
then you could define WagonDetail:
class WagonDetail{
private List<SeatDetail> listSeatDetail;
private int numSeat;
....
}
then class SeatDetail so on
And you could use gson to serialize that class Output pretty easily:
Output output = new Output();
//set according attributes using setter/getter
Gson gson = new Gson();
String jsStr = gson.toJson(output);
Deserialize the JSON string to an object is easily too:
String jsStr = "..."
Gson gson = new Gson();
Output output = gson.fromJson(jsStr, Output.class);

Related

Parse JSON document based on predefined JSON mapping document in Java

I want to get some idea if there is any library in Java that I can use to filter a JSON document based on a predefined JSON mapping document, or only way to achieve this is to write custom java code.
If it's required to write Java custom code what type of design pattern or data structure I should follow. Any advice will be very much appreciated.
Example -
Input JSON document -
{
"basicInfo": {
"name": "name",
"age": "25",
"address": "address"
},
"education": [
{
"ug": {
"unversity": "university",
"major": [
"cs",
"ds"
],
"year": "2012"
},
"pg": {
"unversity": "university",
"major": [
"cs",
"ds"
],
"year": "2015"
}
}
]
}
Predefined JSON mapping document (Can be defined in any JSON format, below is one such example that I have created) -
{
"definitions": {
"basicInfo": {
"maxOccurance": "1",
"fields": [
{
"key": "name",
"type": "S",
"lenght": "50",
"usage": "M",
"maxOccurrance": "1"
},
{
"key": "age",
"type": "S",
"lenght": "3",
"usage": "O",
"maxOccurrance": "1"
}
]
},
"education": {
"maxOccurance": "10",
"fields": [
{
"pg": {
"maxOccurance": "1",
"fields": [
{
"key": "university",
"type": "S",
"lenght": "50",
"usage": "M",
"maxOccurrance": "1"
},
{
"key": "major",
"type": "S",
"lenght": "3",
"usage": "O",
"maxOccurrance": "1"
}
]
}
}
]
}
}
}
Expected output JSON document
{
"basicInfo": {
"name": "name",
"age": "25"
},
"education": [
{
"pg": {
"unversity": "university",
"major": "cs"
}
}
]
}
The request is for a way to filter a JSON document based on a predefined JSON spec sheet / JSON mapping document. The jolt library would likely be able to meet this requirement.

How to find and update nested array element in an object on mongodb

I have a collection down below. I am trying to update an array element.
I am trying to update if lineItem _id value is 1 then go to spec list and update characteristicsValue from 900 to 50 if specName is "Model", as you can see, _id is also an array.
collection data:
{
"_id": "100",
"name": "Campaign",
"status": "Active",
"parts": {
"lineItem": [
{
"_id": [
{
"name": "A",
"value": "1"
}
],
"spec": [
{
"specName": "Brand",
"characteristicsValue": [
{
"value": "500"
}
]
},
{
"specName": "Model",
"characteristicsValue": [
{
"value": "900"
}
]
}
]
},
{
"_id": [
{
"name": "B",
"value": "2"
}
],
"spec": [
{
"specName": "Brand",
"characteristicsValue": [
{
"value": "300"
}
]
},
{
"specName": "Model",
"characteristicsValue": [
{
"value": "150"
}
]
}
]
},
{
"_id": [
{
"name": "C",
"value": "2"
}
]
}
]
}
}
related update doesnt work as I expected.
db.Collection.update({"parts.lineItem._id.value" : "1",
"parts.lineItem.spec.specName" : "Model" },{ $set: {
"parts.lineItem.spec.$.characteristicsValue" : "50" } })
EDIT:
Every _id has a spec array. so, we need to find _id and then go to spec under _id array, find the brand and update the value.
Try this way:
db.Collection.update(
{},
{ $set: { "parts.lineItem.$[outer].spec.$[inner].characteristicsValue" : "50" } },
{ multi: true, arrayFilters: [{"outer._id.value" : "1"}, {"inner.specName" : "Model"}]}
);

Get Nested JSONObject Java?

I am trying to get a JSON object nested inside another JSON object. When I run my main class:
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, JSONException {
NBAPlayers players = new NBAPlayers();
JSONObject json = players.readJsonFromUrl("http://data.nba.net/10s/prod/v1/2017/players.json");
JSONObject League = json.getJSONObject("league");
JSONObject standard =League.getJSONObject("standard");
JSONObject firstName = standard.getJSONObject("firstName");
}
}
I get the error:
Exception in thread "main" org.json.JSONException:
JSONObject["standard"] is not a JSONObject.
I am using the the maven artifact org.json:json package.
This is a part of json that returns url in the example
{
"_internal": {
"pubDateTime": "2017-12-10 11:42:23.504",
"xslt": "xsl/league/roster/marty_active_players.xsl",
"eventName": "league_roster"
},
"league": {
"standard": [
{
"firstName": "Alex",
"lastName": "Abrines",
"personId": "203518",
"teamId": "1610612760",
"jersey": "8",
"isActive": true,
"pos": "G",
"heightFeet": "6",
"heightInches": "6",
"heightMeters": "1.98",
"weightPounds": "190",
"weightKilograms": "86.2",
"dateOfBirthUTC": "1993-08-01",
"teams": [
{
"teamId": "1610612760",
"seasonStart": "2016",
"seasonEnd": "2017"
}
],
"draft": {
"teamId": "1610612760",
"pickNum": "32",
"roundNum": "2",
"seasonYear": "2013"
},
"nbaDebutYear": "2016",
"yearsPro": "1",
"collegeName": "",
"lastAffiliation": "Spain/Spain",
"country": "Spain"
},
{
"firstName": "Quincy",
"lastName": "Acy",
"personId": "203112",
"teamId": "1610612751",
"jersey": "13",
"isActive": true,
"pos": "F",
"heightFeet": "6",
"heightInches": "7",
"heightMeters": "2.01",
"weightPounds": "240",
"weightKilograms": "108.9",
"dateOfBirthUTC": "1990-10-06",
"teams": [
{
"teamId": "1610612761",
"seasonStart": "2012",
"seasonEnd": "2013"
},
{
"teamId": "1610612758",
"seasonStart": "2013",
"seasonEnd": "2013"
},
{
"teamId": "1610612752",
"seasonStart": "2014",
"seasonEnd": "2014"
},
{
"teamId": "1610612758",
"seasonStart": "2015",
"seasonEnd": "2015"
},
{
"teamId": "1610612742",
"seasonStart": "2016",
"seasonEnd": "2016"
},
{
"teamId": "1610612751",
"seasonStart": "2016",
"seasonEnd": "2017"
}
],
as you can see standard is not an object. It is array.
You should change your code as follows
JSONArray standard =League.getJSONArray("standard");
for (int i = 0; i < standard.length(); i++) {
String firstName = standard.getJSONObject(i).getString("firstName");
}

Could anyone help me to convert the below JSON to java object (List), without a java bean. Am new to JSON

[
{
"id": "1234",
"price": 1000,
"categories": [
"Fashion/Shirt"
],
"category_id": [
"1234564"
],
"gender": "Male",
"brand": "Wonder",
"fashion_composition": [
{
"material": "silk",
"percentage": 78
},
{
"material": "Cotton",
"percentage": 22
}
],
"fashion_season": {
"season": "continuity",
"year_season": 2014
},
"fashion_size": {
"size_type": "US",
"size_description_1": "size",
"size_1_manufacturer": "90",
"size_description_2": "top",
"size_2_manufacturer": "C",
"size_1": [
"90"
],
"size_2": [
"C"
]
}
},
{
"id": "5678",
"price": 1000,
"categories": [
"Fashion/Skirt"
],
"category_id": [
"1234564"
],
"gender": "Female",
"brand": "Wonder",
"fashion_composition": [
{
"material": "silk",
"percentage": 78
},
{
"material": "Cotton",
"percentage": 22
}
],
"fashion_season": {
"season": "continuity",
"year_season": 2014
},
"fashion_size": {
"size_type": "US",
"size_description_1": "size",
"size_1_manufacturer": "90",
"size_description_2": "top",
"size_2_manufacturer": "C",
"size_1": [
"90"
],
"size_2": [
"C"
]
}
}
]
Am using gson-2.2.4.jar
I'm guessing you mean by not writing your own bean for GSON to deserialize to. GSON provides support by having certain JSON types that you can make use of:
Gson gson = new Gson();
final JsonArray jsonElements = gson.fromJson(JSON, JsonArray.class);

Why does REST API response contain the bean name?

I need a response like:
[
{
"id": 1,
"site": "Google",
"name": "abc",
"value": "111",
"level": "BASE",
"character": "&"
},
{
"id": 2,
"site": "Yahoo",
"name": "xyz",
"value": "222",
"level": "ONE",
"character": ";"
}
]
Instead, this is the response I get:
{
"responseObjects": [
[
{
"id": 1,
"site": "Google",
"name": "abc",
"value": "111",
"level": "BASE",
"character": "&"
},
{
"id": 2,
"site": "Yahoo",
"name": "xyz",
"value": "222",
"level": "ONE",
"character": ";"
}
]
]
}
My Response class has the following member:
private final List<Object> responseObjects = new ArrayList<Object>();
public List<Object> getResponseObjects() {
return responseObjects;
}
public void addToResponseObjects(Object responseObject) {
responseObjects.add(responseObject);
}
And in my Resource class I have this code that returns the response:
List<MyBean> responseList = new ArrayList<MyBean>();
.....
.....
.....
response.addToResponseObjects(responseList);
return response;
What changes would I need to do to not have "responseObjects" get added in the response? I only need to have the JSON String/Array in the response.

Categories