Encoding / Decoding Yaml using Jackson not symmetric - java

When I execute the following :
ObjectMapper mapper = new ObjectMapper( new YAMLFactory() );
try {
Map matchReport = mapper
.readValue( new File( "C:\\temp\\test.yaml" ),Map.class );
mapper.writeValue( System.out, matchReport );
}
catch ( Exception e ) {
e.printStackTrace();
}
}
For the following input:
{
"$id": "1",
"$type": "LongoMatch.Core.Store.Project, LongoMatch.Core",
"ID": "ae8a4461-b385-4b80-9a54-2254147820f8",
"Periods": [
{
"$id": "106",
"$type": "LongoMatch.Core.Store.Period, LongoMatch.Core",
"ID": "4e1d0f3f-6dfb-40b0-b7f9-3743c661510d",
"Name": "1",
"Nodes": [
{
"$id": "107",
"$type": "LongoMatch.Core.Store.TimeNode, LongoMatch.Core",
"Name": "1",
"Start": 0,
"Stop": 1275931,
"EventTime": 0,
"Rate": 1.0
}
],
"Team": 0
},
{
"$id": "108",
"$type": "LongoMatch.Core.Store.Period, LongoMatch.Core",
"ID": "79d8422e-0ff0-44bf-836d-cb2f4d41ea53",
"Name": "2",
"Nodes": [
{
"$id": "109",
"$type": "LongoMatch.Core.Store.TimeNode, LongoMatch.Core",
"Name": "2",
"Start": 1275931,
"Stop": 2551862,
"EventTime": 1275931,
"Rate": 1.0
}
],
"Team": 0
}
],
"Timers": [],
"Playlists": []
}
I get the following output:
$id: "1"
$type: "LongoMatch.Core.Store.Project, LongoMatch.Core"
ID: "ae8a4461-b385-4b80-9a54-2254147820f8"
Periods:
- $id: "106"
$type: "LongoMatch.Core.Store.Period, LongoMatch.Core"
ID: "4e1d0f3f-6dfb-40b0-b7f9-3743c661510d"
Name: "1"
Nodes:
- $id: "107"
$type: "LongoMatch.Core.Store.TimeNode, LongoMatch.Core"
Name: "1"
Start: 0
Stop: 1275931
EventTime: 0
Rate: 1.0
Team: 0
- $id: "108"
$type: "LongoMatch.Core.Store.Period, LongoMatch.Core"
ID: "79d8422e-0ff0-44bf-836d-cb2f4d41ea53"
Name: "2"
Nodes:
- $id: "109"
$type: "LongoMatch.Core.Store.TimeNode, LongoMatch.Core"
Name: "2"
Start: 1275931
Stop: 2551862
EventTime: 1275931
Rate: 1.0
Team: 0
Timers: []
Playlists: []
Is there and option to force the [] and {} to be written instead of -?
I tried the CANONICAL_OUTPUT option. But then I get [] and {} but also a lot of other characters.
Is there and option to get exactly the same result after encoding back to a stream?

Related

How to Format Key/Meta data of the JSON Object in PHP

Given the following code snippet:
<?php
require "db_conn.php";
$sql = "SELECT category,product_code,product_name,unit,quantity FROM items INNER JOIN categories ON items.category_id=categories.id";
$res = $conn->query($sql)->fetchAll();
$structured = [];
if ($res) {
foreach ($res as $key => $row)
{
$structured[$row['category']]['items'][] = [
'product_code' => $row['product_code'],
'product_name' => $row['product_name'],
'unit' => $row['unit'],
'quantity' => $row['quantity'],
];
}
echo json_encode([$structured]);
}
outputs the following JSON response:
[{
"BABY ITEMS": {
"items": [{
"product_code": "151128",
"product_name": "BOUNCY BABY WIPES 80'S",
"unit": "CARTON",
"quantity": "5.00"
}]
},
"CONFECTIONS\/PASTRIES": {
"items": [{
"product_code": "130570",
"product_name": "NUVITA FAMILY 75G",
"unit": "CARTON",
"quantity": "1.00"
}, {
"product_code": "115165",
"product_name": "NUVITA MAGIK LEMON CRM 60*2'S",
"unit": "CARTON",
"quantity": "2.00"
}]
},
"HOUSEHOLD ITEMS": {
"items": [{
"product_code": "150278",
"product_name": "BOUNCY BABY DIAPER 10'S MINI",
"unit": "CARTON",
"quantity": "1.00"
}]
}
}]
How do I modify this part of code:
$structured[$row['category']]['items'][]
to output:
"category": "BABY ITEMS",
instead of:
"BABY ITEMS":
The expected JSON is (Handwritten):
[{
"category": "BABY ITEMS",
"items": [{
"product_code": "151128",
"product_name": "BOUNCY BABY WIPES 80'S",
"unit": "CARTON",
"quantity": "5.00"
}]
},
{
"category": "CONFECTIONS/PASTRIES",
"items": [{
"product_code": "130570",
"product_name": "NUVITA FAMILY 75G",
"unit": "CARTON",
"quantity": "1.00"
},
{
"product_code": "115165",
"product_name": "NUVITA MAGIK LEMON CRM 60*2'S",
"unit": "CARTON",
"quantity": "3.00"
},
{
"product_code": "115160",
"product_name": "NUVITA MAGIK S.BERRY CRM 60*2'S",
"unit": "CARTON",
"quantity": "2.00"
}
]
},
{
"category": "HOUSEHOLD ITEMS",
"items": [{
"product_code": "150278",
"product_name": "BOUNCY BABY DIAPER 10'S MINI",
"unit": "CARTON",
"quantity": "1.00"
}]
},
{
"category": "PERSONAL CARE",
"items": [{
"product_code": "160200",
"product_name": "ALL TYME ULTRA REGULAR 8'S",
"unit": "CARTON",
"quantity": "2.00"
},
{
"product_code": "160309",
"product_name": "ALL TYME ULTRA MEDIUM 8'S",
"unit": "CARTON",
"quantity": "4.00"
},
{
"product_code": "160235",
"product_name": "GOLDEN SHOE POLSIH 50ML BLACK",
"unit": "CARTON",
"quantity": "1.00"
},
{
"product_code": "190251",
"product_name": "ALL TYME ULTRA MEDIUM 16'S",
"unit": "CARTON",
"quantity": "2.00"
}]
}
]
I really need the JSON formatted as above as am using it to create a nested category and items RecyclerView. This is how am parsing in android java:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objCategory = jsonArray.getJSONObject(i);
System.out.println("Category: " + objCategory.getString("category"));
// fetch item details and store it in arraylists
JSONArray itemArray = objCategory.getJSONArray("items");
//System.out.println("Item length: " + itemArray.length());
ParentItem category = new
ParentItem(objCategory.getString("category"),OrderItemsList(itemArray));
orderFetchingList.add(category);
}
Please see the following code (fully functional). I mocked $res with few records and copied your code to fill $structured. Below that, please find my code to restructure the data in order the get the desired JSON output
$res = [
[
'category' => 'BABY',
'product_code' => '123',
'product_name' => 'BABY STUFF',
'unit' => 1,
'quantity' => 999,
],
[
'category' => 'BABY',
'product_code' => '125',
'product_name' => 'BABY EAT',
'unit' => 1,
'quantity' => 999,
],
[
'category' => 'MEN',
'product_code' => '124',
'product_name' => 'MEN STUFF',
'unit' => 2,
'quantity' => 888,
]
];
echo '<pre>';
$structured = [];
foreach($res as $key => $row) {
$structured[$row['category']]['items'][] = [
'product_code' => $row['product_code'],
'product_name' => $row['product_name'],
'unit' => $row['unit'],
'quantity' => $row['quantity'],
];
}
print_r($structured);
// restructure the data to get the desired JSON output
$collection = [];
foreach($structured as $category => $items) {
$collection[] = [
'category' => $category,
'items' => $items['items']
];
}
echo json_encode($collection);
Output (JSON):
[
{
"category": "BABY",
"items": [
{
"product_code": "123",
"product_name": "BABY STUFF",
"unit": 1,
"quantity": 999
},
{
"product_code": "125",
"product_name": "BABY EAT",
"unit": 1,
"quantity": 999
}
]
},
{
"category": "MEN",
"items": [
{
"product_code": "124",
"product_name": "MEN STUFF",
"unit": 2,
"quantity": 888
}
]
}
]

How to Iterate through Json schema and values based on keys

I have this JSON schema. I want to read it line by line and populate all "name" key values to an ArrayList of String until it reaches a key called entity. When it reaches to an entity I want to read the entity value and populate it to a String.After that loop should go through the remains of the schema and read all the "name" and populate to a new ArrayList until it meets another entity and so on...
I've only included a part of the schema it's a valid schema.
{
"entity": "Data",
"xement": [
{
"code": "MA",
"entity": "MH",
"attr": [
{
"name": "Id",
"position": 1
},
{
"name": "mdc",
"position": 4
},
{
"name": "minr",
"position": 10
},
{
"name": "mx",
"position": 11
}
],
"maltr": [
{
"name": "sub",
"position": 13
}
]
},
{
"code": "war",
"entity": "subl",
"attr": [
{
"name": "se",
"position": 1
},
{
"name": "go",
"position": 2
},
{
"name": "re",
"position": 4
},
{
"name": "pr",
"position": 10
},
{
"name": "mxp",
"position": 11
},
{
"name": "rpl",
"position": 45
},
{
"name": "rtr",
"position": 47
},
{
"name": "net",
"position": 55
}
],
"groups": [
{
"entity": "ro",
"grattr": [
{
"name": "rmn",
"position": 5
},
{
"name": "aib",
"position": 6
},
{
"name": "nxr",
"position": 7
},
{
"name": "xer",
"position": 8
},
{
"name": "rog",
"position": 9
},
{
"name": "ccc",
"position": 16
}
]
}
]
}
]
}
What is the best way to do that?

MongoDB query and select inner object

I want to query for inner object and select only filtered inner objects from mongoddb document.
Consider below mongodb document.
{
"schools": [
{
"name": "ABC",
"students": [
{
"name": "ABC 1",
"class": 1
},
{
"name": "ABC 2",
"class": 2
},
{
"name": "ABC 3",
"class": 1
}
]
},
{
"name": "XYZ",
"students": [
{
"name": "XYZ 1",
"class": 1
},
{
"name": "XYZ 2",
"class": 2
}
]
}
]
}
I want to select only students in class 1.
expected result json as below.
{
"school": {
"name": "ABC",
"students": [
{
"name": "ABC 1",
"class": 1
},
{
"name": "ABC 3",
"class": 1
}
]
},
"school": {
"name": "XYZ",
"students": [
{
"name": "XYZ 1",
"class": 1
}
]
}
}
Even below result is fine with me.
{
"students": [
{
"name": "ABC 1",
"class": 1
},
{
"name": "ABC 3",
"class": 1
},
{
"name": "XYZ 1",
"class": 1
}
]
}
Please help me to get this done.
Really helpful if can provide mongodb query.
I am using mongodb with spring data in my application.
You can search for mongo db array nested record search. The example code is here. Document is here.
db.your_collection_name.find({'school.student.class':1})
If you only want students do flatmap for your results. Here is document for flatmap in mongodb
Finally I could be able to find the query.
First I have to unwind and apply matching criteria. this was work for me.
db.{mycollection}.aggregate(
[
{ $unwind: '$schools.students'},
{ $match : { "schools.students.class" : 1 } },
{ $project : { "schools.name" : 1, 'schools.students' : 1 } }
]
);

How to split JSON into Dataset rows?

I have the following JSON input data:
{
"lib": [
{
"id": "a1",
"type": "push",
"icons": [
{
"iId": "111"
}
],
"id": "a2",
"type": "pull",
"icons": [
{
"iId": "111"
},
{
"iId": "222"
}
]
}
]
I want to get the following Dataset:
id type iId
a1 push 111
a2 pull 111
a2 pull 222
How can I do it?
This is my current code. I use Spark 2.3 and Java 1.8:
ds = spark
.read()
.option("multiLine", true).option("mode", "PERMISSIVE")
.json(jsonFilePath);
ds = ds
.select(org.apache.spark.sql.functions.explode(ds.col("lib.icons")).as("icons"));
However the result is wrong:
+---------------+
| icons|
+---------------+
| [[111]]|
|[[111], [222...|
+---------------+
How can I get the correct Dataset?
UPDATE:
I tries this code, but it generates some extra combinations of id, type and iId that do not exist in the input file.
ds = ds
.withColumn("icons", org.apache.spark.sql.functions.explode(ds.col("lib.icons")))
.withColumn("id", org.apache.spark.sql.functions.explode(ds.col("lib.id")))
.withColumn("type", org.apache.spark.sql.functions.explode(ds.col("lib.type")));
ds = ds.withColumn("its", org.apache.spark.sql.functions.explode(ds.col("icons")));
As already pointed out, the JSON String seems to be malformed. with the updated one, you can use the following to get result you wanted:
import org.apache.spark.sql.functions._
spark.read
.format("json")
.load("in/test.json")
.select(explode($"lib").alias("result"))
.select($"result.id", $"result.type", explode($"result.icons").alias("iId"))
.select($"id", $"type", $"iId.iId")
.show
Your JSON appears to be malformed. Fixing the indenting makes this slightly more apparent:
{
"lib": [
{
"id": "a1",
"type": "push",
"icons": [
{
"iId": "111"
}
],
"id": "a2",
"type": "pull",
"icons": [
{
"iId": "111"
},
{
"iId": "222"
}
]
}
]
Does your code work correctly if you feed it this JSON instead?
{
"lib": [
{
"id": "a1",
"type": "push",
"icons": [
{
"iId": "111"
}
]
},
{
"id": "a2",
"type": "pull",
"icons": [
{
"iId": "111"
},
{
"iId": "222"
}
]
}
]
}
Note the inserted }, { just before "id": "a2" to break the object with duplicate keys into two, and the closing } at the very end which had previously been omitted.

Json query String for getting value with Condition

I want to get the value of vehicleCodeelement where vehicleLease is AS PER LAW OF ENFORCMENT.
Could someone please help me with JSON query ?
Please find JSON data below.
{
"StateOffers": [
[{
"vehicleCode": 242214214,
"vehiclePart": [{
"#type": "vehiclePart",
"segments": [{
"#type": "Segment"
"segmentOfferInformation": {
"vehicleMiles": 771,
"awardFare": false
},
"vehicleLease": "AS PER LAW OF ENFORCMENT"
}
],
"stops": 0
}
]
}, {
"vehicleCode": 242214214,
"vehiclePart": [{
"#type": "vehiclePart",
"segments": [{
"#type": "Segment"
"segmentOfferInformation": {
"vehicleMiles": 771,
"awardFare": false
},
"vehicleLease": "MY RULE MY WORLD"
}
],
"stops": 0
}
]
}
]
]
}
This is the expression I have tried:
$..vehicleCode[?($..vehicleLease=="AS PER LAW OF ENFORCMENT")

Categories