object to json in spring - json

Below is the code snippet from different project files
ProjectRepository.java
#Query(value=" SELECT p.id as project_id,p.project_status, t.id as test_suite_id, t.test_suite_status, ts.id as test_script_id,ts.test_script_status, tss.id as test_step_id, tss.test_step_status FROM project p LEFT OUTER JOIN test_suite t ON (p.id = t.project_id AND t.test_suite_status = 1) LEFT OUTER JOIN test_script ts ON (t.id = ts.test_suite_id AND ts.test_script_status=1) LEFT OUTER JOIN test_step tss ON (ts.id = tss.test_script_id AND tss.test_step_status=1) where p.team_id=:teamId and p.project_status=1 ",nativeQuery=true)
public List<Object> getActiveProjectsWithTeamId(#Param("teamId") Long teamId);
projectService.java
List<Object> findActiveProjectsByTeamId(Long id) throws DAOException;
projectServiceImpl.java
#Override
#Transactional(readOnly = true)
public List<Object> findActiveProjectsByTeamId(Long id) throws DAOException {
log.info("entered into ProjectServiceImpl:findOneByTeamId");
if (id != null) {
try {
// returns all projects of the specified team whose
// project_status is active
List<Object> project=projectRepository.getActiveProjectsWithTeamId(id);
return project;
} catch (Exception e) {
log.error("Exception raised while retrieving the project of the mentioned ID from database : "
+ e.getMessage());
throw new DAOException("Exception occured while retrieving the required project");
} finally {
log.info("exit from ProjectServiceImpl:findOneByTeamId");
}
}
return null;
}
I am getting below Output-
[ [ 1, true, 1, true, null, null, null, null ], [ 1, true, 2, true, null, null, null, null ], [ 1, true, 3, true, null, null, null, null ], [ 1, true, 5, true, null, null, null, null ], [ 1, true, 6, true, null, null, null, null ] ]
but I want the result in key value pair

Related

How to get List from api in flutter

I'm Trying to get a list of users from my api through ApiService and model it in my UserModel class.
It's giving me this error The argument type 'List<Result>?' can't be assigned to the parameter type 'List<Result>'.
The results are also not showing on the screen.
Much obliged
If the provided code is not enough and you want to take a look at the full project, here's the repo:
https://github.com/renslakens/SkoolWorkshopApp.git
UserModel class
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
class UserModel {
UserModel({
required this.status,
required this.result,
});
int status;
List<Result> result;
factory UserModel.fromJson(Map<String, dynamic> json) =>
UserModel(
status: json["status"] == null ? null : json["status"],
result: json["result"] == null ? null : List<Result>.from(
json["result"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() =>
{
"status": status == null ? null : status,
"result": result == null ? null : List<dynamic>.from(result.map((x) => x.toJson())),
};
}
class Result {
Result userModelFromJson(String str) => Result.fromJson(json.decode(str));
String userModelToJson(UserModel data) => json.encode(data.toJson());
Result({
required this.docentId,
required this.naam,
required this.achternaam,
required this.emailadres,
required this.geboortedatum,
required this.geboorteplaats,
this.maxRijafstand,
this.heeftRijbewijs,
this.heeftAuto,
required this.straat,
required this.huisnummer,
required this.geslacht,
required this.nationaliteit,
required this.woonplaats,
required this.postcode,
required this.land,
required this.wachtwoord,
required this.isAccepted,
this.isFlexwerker,
});
int docentId;
String naam;
String achternaam;
String emailadres;
String geboortedatum;
String geboorteplaats;
dynamic maxRijafstand;
dynamic heeftRijbewijs;
dynamic heeftAuto;
String straat;
int huisnummer;
String geslacht;
String nationaliteit;
String woonplaats;
String postcode;
String land;
String wachtwoord;
int isAccepted;
dynamic isFlexwerker;
factory Result.fromJson(Map<String, dynamic> json) =>
Result(
docentId: json["docentID"] == null ? null : json["docentID"],
naam: json["naam"] == null ? null : json["naam"],
achternaam: json["achternaam"] == null ? null : json["achternaam"],
emailadres: json["emailadres"] == null ? null : json["emailadres"],
geboortedatum: json["geboortedatum"] == null ? null : (json["geboortedatum"]),
geboorteplaats: json["geboorteplaats"] == null
? null
: json["geboorteplaats"],
maxRijafstand: json["maxRijafstand"],
heeftRijbewijs: json["heeftRijbewijs"],
heeftAuto: json["heeftAuto"],
straat: json["straat"] == null ? null : json["straat"],
huisnummer: json["huisnummer"] == null ? null : json["huisnummer"],
geslacht: json["geslacht"] == null ? null : json["geslacht"],
nationaliteit: json["nationaliteit"] == null
? null
: json["nationaliteit"],
woonplaats: json["woonplaats"] == null ? null : json["woonplaats"],
postcode: json["postcode"] == null ? null : json["postcode"],
land: json["land"] == null ? null : json["land"],
wachtwoord: json["wachtwoord"] == null ? null : json["wachtwoord"],
isAccepted: json["isAccepted"] == null ? null : json["isAccepted"],
isFlexwerker: json["isFlexwerker"],
);
Map<String, dynamic> toJson() =>
{
"docentID": docentId == null ? null : docentId,
"naam": naam == null ? null : naam,
"achternaam": achternaam == null ? null : achternaam,
"emailadres": emailadres == null ? null : emailadres,
"geboortedatum": geboortedatum == null ? null : geboortedatum,
"geboorteplaats": geboorteplaats == null ? null : geboorteplaats,
"maxRijafstand": maxRijafstand,
"heeftRijbewijs": heeftRijbewijs,
"heeftAuto": heeftAuto,
"straat": straat == null ? null : straat,
"huisnummer": huisnummer == null ? null : huisnummer,
"geslacht": geslacht == null ? null : geslacht,
"nationaliteit": nationaliteit == null ? null : nationaliteit,
"woonplaats": woonplaats == null ? null : woonplaats,
"postcode": postcode == null ? null : postcode,
"land": land == null ? null : land,
"wachtwoord": wachtwoord == null ? null : wachtwoord,
"isAccepted": isAccepted == null ? null : isAccepted,
"isFlexwerker": isFlexwerker,
};
}
APIService class
class ApiService {
Future<List<UserModel>> getUsers() async {
try {
var url = Uri.parse(apis.baseUrl + apis.getUsers);
var response = await http.get(url);
if (response.statusCode == 200) {
List<UserModel> model = userModelFromJson(response.body);
return model;
}
} catch (e) {
log(e.toString());
}
}
}
Results from the API to list all the imported users
{
"status": 200,
"result": [
{
"docentID": 1,
"naam": "gerrit",
"achternaam": "petersen",
"emailadres": "meel#meel.com",
"geboortedatum": "1899-11-29T23:40:28.000Z",
"geboorteplaats": "",
"maxRijafstand": null,
"heeftRijbewijs": null,
"heeftAuto": null,
"straat": "",
"huisnummer": 0,
"geslacht": "",
"nationaliteit": "",
"woonplaats": "",
"postcode": "",
"land": "",
"wachtwoord": "$2b$10$kcVpe9yOdKzMPdEUcMIATOh3PE42GDiQfDLZeufKxpLpTb51Af7Ay",
"isAccepted": 0,
"isFlexwerker": null
},
{
"docentID": 4,
"naam": "gerrit",
"achternaam": "petersen",
"emailadres": "123mail123#meel.com",
"geboortedatum": "1899-11-29T23:40:28.000Z",
"geboorteplaats": "",
"maxRijafstand": null,
"heeftRijbewijs": null,
"heeftAuto": null,
"straat": "",
"huisnummer": 0,
"geslacht": "",
"nationaliteit": "",
"woonplaats": "",
"postcode": "",
"land": "",
"wachtwoord": "$2b$10$jNx8CrBRw78VZdoTTomGWuVF4CEa6wcMMsIzmkHak1WjRVsfHaX86",
"isAccepted": 0,
"isFlexwerker": null
},
{
"docentID": 7,
"naam": "Peter",
"achternaam": "gerritsen",
"emailadres": "test1#meel.com",
"geboortedatum": "1899-11-29T23:40:28.000Z",
"geboorteplaats": "",
"maxRijafstand": null,
"heeftRijbewijs": null,
"heeftAuto": null,
"straat": "",
"huisnummer": 0,
"geslacht": "",
"nationaliteit": "",
"woonplaats": "",
"postcode": "",
"land": "",
"wachtwoord": "$2b$10$JRbNe40U7Fk2hcA4B4bgEe9ElmCX5dCovf5FNtZTLHLCX8v/DeiN2",
"isAccepted": 0,
"isFlexwerker": null
}
]
}

How To extract Value from Json multi dimension Array In MySQL

column contain value given below.
[
{
"bActive": false,
"sSubLocation": "",
"aiSeries": [],
"iUser": "1"
},
{
"bActive": true,
"sSubLocation": "Mytestcase",
"aiSeries": [],
"iUser": "1"
}
]
I want to get result as sSubLocation key where it have bActive =true and sSubLocation = "Mytestcase";
SELECT test.id, jsontable.*
FROM test
CROSS JOIN JSON_TABLE(test.value,
'$[*]' COLUMNS (bActive BOOLEAN PATH '$.bActive',
sSubLocation VARCHAR(255) PATH '$.sSubLocation',
aiSeries JSON PATH '$.aiSeries',
iUser VARCHAR(255) PATH '$.iUser')) jsontable
HAVING bActive = true
AND sSubLocation = 'Mytestcase'
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=bcf7f238e23a2c282cdea76c183ae8fa

Fetch all records from table A where id = somvalue in B plus records which don't have id in B

I have two tables a coupons table and a coupon_city_map table.
id
coupon_code
1
OFFER20
2
OFFER10
3
OFFER50
4
OFFER40
5
OFFER90
coupon_Id
city_id
1
2
2
3
3
4
4
2
I need coupons with ids 1 4, and 5 for city_id = 2.
So It should fetch all the coupons where city_id=2 i.e. coupons with id 1 and 4
and it should also fetch coupons which don't have key in coupon_city_map i.e 5.
This is what I have tried but the query in [Op.or] is not working, and it returns all the coupons instead.
let coupons = await Coupon.findAll({
where: {
[Op.or]: [
{ '$CouponCities.city_id$': city_id },
{ '$CouponCities.coupon_id$': null },
],
...filters // other filter like is_active: true
},
include: {
model: CouponCity,
attributes: [],
},
attributes: ['id', 'coupon_code', 'discount_per', 'flat_discount', 'discount_upto', 'description', 'display'],
});
The query being generated
SELECT `Coupon`.`id`,
`Coupon`.`coupon_code`,
`Coupon`.`discount_per`,
`Coupon`.`flat_discount`,
`Coupon`.`discount_upto`,
`Coupon`.`description`,
`Coupon`.`display`
FROM `coupons` AS `Coupon`
LEFT OUTER JOIN `coupon_city_map` AS `CouponCities` ON `Coupon`.`id` = `CouponCities`.`coupon_id`
WHERE (`Coupon`.`user_id` IS NULL OR `Coupon`.`user_id` = 1)
AND `Coupon`.`is_active` = true
AND `Coupon`.`is_external` = false
AND `Coupon`.`start_date` < '2020-12-30 10:33:20'
AND `Coupon`.`expiry_date` > '2020-12-30 10:33:20';
Update
I also tried below, but still it is returning all the coupons.
let coupons = await Coupon.findAll({
// where: {
// ...filters,
// },
include: {
model: CouponCity,
required: false,
where: {
[Op.or]: [
{
zone_id: zoneId,
}, {
coupon_id: null,
},
],
},
attributes: [],
},
attributes: ['id', 'coupon_code', 'discount_per', 'flat_discount','discount_upto', 'description', 'display'],
});
...and it generates below query.
SELECT `Coupon`.`id`,
`Coupon`.`coupon_code`,
`Coupon`.`discount_per`,
`Coupon`.`flat_discount`,
`Coupon`.`discount_upto`,
`Coupon`.`description`,
`Coupon`.`display`
FROM `coupons` AS `Coupon`
LEFT OUTER JOIN `coupon_city_map` AS `CouponCities`
ON `Coupon`.`id` = `CouponCities`.`coupon_id`
AND ( `CouponCities`.`zone_id` = 1
AND `CouponCities`.`coupon_id` IS NULL )
WHERE `Coupon`.`is_active` = true
AND `Coupon`.`is_external` = false;
This is what worked for me, query is mess but it works. I am posting all the codes for better understanding for anyone interested.
Here zone is city.
{
const filters = {
start_date: {
[Op.lt]: new Date(),
},
expiry_date: {
[Op.gt]: new Date(),
},
};
if (userId) {
filters[Op.or] = [{
user_id: null,
}, {
user_id: userId,
}];
filters[Op.and] = {
[Op.or]: [
sequelize.literal('CouponZones.zone_id = 1'),
sequelize.literal('CouponZones.coupon_id IS null')
],
};
} else {
filters.user_id = null;
}
let coupons = await Coupon.findAll({
where: {
...filters,
},
include: {
model: CouponZone,
attributes: [],
},
attributes: ['id', 'coupon_code', 'discount_per', 'flat_discount', 'discount_upto', 'description', 'display'],
});
This is the query it generates.
SELECT `Coupon`.`id`,
`Coupon`.`coupon_code`,
`Coupon`.`discount_per`,
`Coupon`.`flat_discount`,
`Coupon`.`discount_upto`,
`Coupon`.`description`,
`Coupon`.`display`
FROM `coupons` AS `Coupon`
LEFT OUTER JOIN `coupon_zone_map` AS `CouponZones`
ON `Coupon`.`id` = `CouponZones`.`coupon_id`
WHERE ( `Coupon`.`user_id` IS NULL
OR `Coupon`.`user_id` = 1 )
AND ((CouponZones.zone_id = 1 OR CouponZones.coupon_id IS null))
AND `Coupon`.`is_active` = true
AND `Coupon`.`is_external` = false;
Use UNION
You can write query like below
SELECT coupons.*
FROM coupons,
coupon_city_map
WHERE coupons.id = coupon_city_map.coupon_id
AND coupon_city_map.city_id = 2
UNION
SELECT coupons.*
FROM coupons
WHERE coupons.id NOT IN(SELECT coupon_city_map.coupon_id
FROM coupon_city_map)

Updating nested JSON sub-arrays by various keys

I am using SQL Server 2016 version, I can't tell if this is something specific to this version or whether I am missing something. I am trying to update a common property, node_status, inside an array of objects. The SQL update I am running to update node_status where is_node_complete: false is only updating the first index it finds rather than all that fit the query for node_status.
The JSON structure inside column json_doc in some_table
{
"personnel": [
{
"node_id": "FDA64E9F-3BAC-45FA-8819-8A086D96B359",
"node_data": {
"is_approved": null,
"is_node_complete": false,
"node_status": "requested"
}
},
{
"node_id": "AF829232-32F4-464B-8817-50ED24447AA4",
"node_data": {
"is_approved": null,
"is_node_complete": false,
"node_status": "requested"
}
},
{
"node_id": "E18F8197-B16D-4E0B-8EE9-DBF5B23A8EB5",
"node_data": {
"is_approved": true,
"is_node_complete": true,
"node_status": "complete"
}
},
{
"node_id": "286700AE-81C8-4F4F-955D-D8DCE44ED30C",
"node_data": {
"is_approved": false,
"is_node_complete": true,
"node_status": "complete"
}
},
{
"node_id": "BC7BD024-70F1-459B-BDBF-945A3EED666C",
"node_data": {
"is_approved": null,
"is_node_complete": false,
"node_status": "requested"
}
}
]
}
My query to update column
DECLARE #rec_id INT = 1;;
WITH personnel_CTE
AS (
SELECT *
FROM some_table AS acm
CROSS APPLY openjson(json_doc) WITH (personnel_node NVARCHAR(MAX) '$.personnel' AS json)
CROSS APPLY openjson(personnel_node) pn
WHERE id = #rec_id
AND cast(json_value(pn.value, '$.node_data.is_node_complete') AS BIT) = 0
)
UPDATE personnel_CTE
SET json_doc = json_modify(json_doc, '$.personnel[' + personnel_CTE.[key] + '].node_data.node_status', 'reviewer_assigned')
The guids are unique as well as the id for some_table. This is a truncated toy example, but these properties are the key items for the update.
I don't think that you can update the JSON content with this statement (updating one row with values from multiple rows), but you may try with the following approach, which parses the JSON data as a table using OPENJSON(), updates this table and outputs the table's content as JSON using FOR JSON PATH:
JSON:
DECLARE #json nvarchar(max) = N'
{
"personnel": [
{
"node_id": "FDA64E9F-3BAC-45FA-8819-8A086D96B359",
"node_data": {
"is_approved": null,
"is_node_complete": false,
"node_status": "requested"
}
},
{
"node_id": "AF829232-32F4-464B-8817-50ED24447AA4",
"node_data": {
"is_approved": null,
"is_node_complete": false,
"node_status": "requested"
}
},
{
"node_id": "E18F8197-B16D-4E0B-8EE9-DBF5B23A8EB5",
"node_data": {
"is_approved": true,
"is_node_complete": true,
"node_status": "complete"
}
},
{
"node_id": "286700AE-81C8-4F4F-955D-D8DCE44ED30C",
"node_data": {
"is_approved": false,
"is_node_complete": true,
"node_status": "complete"
}
},
{
"node_id": "BC7BD024-70F1-459B-BDBF-945A3EED666C",
"node_data": {
"is_approved": null,
"is_node_complete": false,
"node_status": "requested"
}
}
]
}'
Table and statement:
CREATE TABLE some_table (id int, json_doc nvarchar(max))
INSERT INTO some_table (id, json_doc) VALUES (1, #json)
INSERT INTO some_table (id, json_doc) VALUES (2, #json)
DECLARE #rec_id INT = 1;
UPDATE some_table
SET json_doc = (
SELECT
node_id AS 'node_id',
is_approved AS 'node_data.is_approved',
is_node_complete AS 'node_data.is_node_complete',
CASE
WHEN CONVERT(bit, is_node_complete) = 0 THEN 'reviewer_assigned'
ELSE node_status
END AS 'node_data.node_status'
FROM OPENJSON (json_doc, '$.personnel') WITH (
node_id nvarchar(36) '$.node_id',
is_approved bit '$.node_data.is_approved',
is_node_complete bit '$.node_data.is_node_complete',
node_status nvarchar(50) '$.node_data.node_status'
)
FOR JSON PATH, ROOT ('personnel'), INCLUDE_NULL_VALUES
)
WHERE id = #rec_id

Postgres + Sequelize: How to read function result?

I have a function payment_summary() as below:
CREATE OR REPLACE FUNCTION payment_summary()
RETURNS SETOF PAYMENT_SUMMARY_TYPE
LANGUAGE plpgsql
AS $$
DECLARE
payment_sum payment_summary_type%ROWTYPE;
BEGIN
FOR payment_sum IN SELECT
pay.application_no,
project.title,
pay.payment_rec,
customer.cust_name,
project.estimated_cost,
(project.estimated_cost - pay.payment_rec) AS outstanding_amt
FROM project
INNER JOIN customer
ON project.customer_cust_id = customer.cust_id
INNER JOIN
(SELECT
project.application_no,
sum(payment.amount) AS payment_rec
FROM payment
INNER JOIN project
ON payment.project_id = project.project_id
WHERE payment.drcr_flg = 'Cr'
GROUP BY project.application_no) AS pay
ON pay.application_no = project.application_no
LOOP
RETURN NEXT payment_sum;
END LOOP;
END;
$$;
PAYMENT_SUMMARY_TYPE is defined as:
CREATE TYPE PAYMENT_SUMMARY_TYPE AS
(
application_no VARCHAR(150),
title VARCHAR(500),
payment_rec INTEGER,
customer_name VARCHAR(500),
estimated_cost INTEGER,
outstanding_amt INTEGER
);
Using below code to execute the function and get results:
sequelize.query('SELECT payment_summary()').then(function(data) {
res.json(data);
});
Getting below as response:
[
[
{
"payment_summary": "(716,\"C1\",100000,\"C1 - city\",0,-100000)"
},
{
"payment_summary": "(716,\"C2\",100000,\"C2 - city\",0,-100000)"
}
],
{
"command": "SELECT",
"rowCount": 2,
"oid": null,
"rows": [
{
"payment_summary": "(716,\"C1\",100000,\"C1 - city\",0,-100000)"
},
{
"payment_summary": "(716,\"C2\",100000,\"C2 - city\",0,-100000)"
}
],
"fields": [
{
"name": "payment_summary",
"tableID": 0,
"columnID": 0,
"dataTypeID": 17453,
"dataTypeSize": -1,
"dataTypeModifier": -1,
"format": "text"
}
],
"_parsers": [
null
],
"rowAsArray": false
}
]
I need the response in below format:
[
{
application_no: 716,
title: "C1",
payment_rec : 100000,
customer_name : "C1 - city"
estimated_cost : 0
outstanding_amt : -100000
},
{
application_no: 717,
title: "C2",
payment_rec : 100000,
customer_name : "C2 - city"
estimated_cost : 0
outstanding_amt : -100000
}
]
How can i read / convert the response in required format ?