Merge all Nested Json Objects - c#

I have got a following json. I want to merge all nested json objects into one.
[
{
"2": "a",
"3": "a"
},
{
"2": "f",
"3": "a",
"4": "p"
},
{
"2": "n",
"3": "o",
"4": "t"
}
]
so, the output of the above json would be
[
{
"0":"a",
"1":"a",
"2":"f",
"3":"a",
"4":"p",
"5":"n",
"6":"o",
"7":"t"
}
]
I tried to parse the json array and then add all values and append it to another array. However, is there any other elegant solution to merge all nested json objects to one?

Given that you need to change indices, manual merging is unavoidable.
E.g. SelectMany from Linq could be used for merging as:
var input = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(#"
[
{
""2"": ""a"",
""3"": ""a""
},
{
""2"": ""f"",
""3"": ""a"",
""4"": ""p""
},
{
""2"": ""n"",
""3"": ""o"",
""4"": ""t""
}
]");
var result = input
.SelectMany(d => d.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
.Select((value, index) => new {index, value})
.ToDictionary(iv => iv.index, iv => iv.value);
var jsonResult = JsonConvert.SerializeObject(result);

You can use the tool called json .net
Check the following code :
var serializer = new XmlSerializer(model.GetType());
serializer.Serialize(sw, model);
JObject o1 = JObject.Parse(#"{
'FirstName': 'John',
'LastName': 'Smith',
'Enabled': false,
'Roles': [ 'User' ]
}");
JObject o2 = JObject.Parse(#"{
'Enabled': true,
'Roles': [ 'User', 'Admin' ]
}");
o1.Merge(o2, new JsonMergeSettings
{
// union array values together to avoid duplicates
MergeArrayHandling = MergeArrayHandling.Union
});
string json = o1.ToString();
// {
// "FirstName": "John",
// "LastName": "Smith",
// "Enabled": true,
// "Roles": [
// "User",
// "Admin"
// ]
// }
Please Check Link :
https://www.newtonsoft.com/json/help/html/MergeJson.htm

Related

UpdateExpression to flatten the record

I have such items in Dynamo DB:
[{
"Id": "1",
"Data": {
"Value": "test"
}
},
{
"Id": "2",
"Data": {}
},
{
"Id": "3"
},
{
"Id": "4",
"Data": {
"Wrong": "234"
}
}]
And I'm trying to make it flatten, but for the Data.Value field only:
[{
"Id": "1",
"Value": "test"
},
{
"Id": "2"
},
{
"Id": "3"
},
{
"Id": "4"
}]
My Update request looks like this:
var request = new UpdateItemRequest {
TableName = "<table>",
Key = new Dictionary<string, AttributeValue> {{"Id", new AttributeValue("<item-id>")}},
UpdateExpression = "SET #a = #c.#a REMOVE #c",
ExpressionAttributeNames = new Dictionary<string, string> {
{"#c", "Data"},
{"#a", "Value"}
}
};
This works well for Id = 1 and 3. But does not work for 2 and 4. I assume because it can not do a SET. It does not throw any errors, but simply does not delete the Data attribute.
Is there a way to make it in a single call?
you just need a condition with your expression, to check if the attribute exist or not, thats it.
ConditionExpression ="attribute_exists (#c.#a)"
For more détails in Amazon doncs here.

Insert Key value pair into existing JSON in C#

I have a json like below
{
"name": "Ram",
"Age": "25",
"ContactDetails": {
"MobNo": "1"
}
}
Please suggest how to add
"Address": {
"No": "123",
"Street": "abc"
}
into ContactDetails
This should work (using Newtonsoft.Json)
var json =
#"{
""name"": ""Ram"",
""Age"": ""25"",
""ContactDetails"": {
""MobNo"": ""1""
}
}";
var jObject = JObject.Parse(json);
jObject["ContactDetails"]["Address"] = JObject.Parse(#"{""No"":""123"",""Street"":""abc""}");
var resultAsJsonString = jObject.ToString();
The result is:
{
"name": "Ram",
"Age": "25",
"ContactDetails": {
"MobNo": "1",
"Address": {
"No": "123",
"Street": "abc"
}
}
}
One of the options would be use Newtonsoft's Json.NET to parse json into JObject, find needed token, and add property to it:
var jObj = JObject.Parse(jsonString);
var jObjToExtend = (JObject)jObj.SelectToken("$.ContactDetails");
jObjToExtend.Add("Address", JObject.FromObject(new { No = "123", Street = "abc" }));
Just Deserialize the JSON into object, then insert the value that you need to insert to it.
Then, Serialize the object into JSON.
Reference: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to

Querying a subfield in documentdb

For example I have a document below for collection = delivery:
{
"doc": [
{
"docid": "15",
"deliverynum": "123",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
},
{
"docid": "16",
"deliverynum": "456",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
},
{
"docid": "17",
"deliverynum": "999",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
}
],
"id": "123",
"cancelled": false
}
is it possible to do a search with "deliverynum" = 999 and the output would be like below?
{
"doc": [
{
"docid": "17",
"deliverynum": "999",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
}
],
"id": "123",
"cancelled": false
}
or should I make another Collection just for the Doc part?
I am having trouble making a query in C# for this kind of scenario.
In Mongo shell you can use the $(projection) operator:
db.collection.find({ "doc.deliverynum": "999" }, { "doc.$": 1 })
Corresponding C# code can look like below:
var q = Builders<Model>.Filter.ElemMatch(x => x.doc, d => d.deliverynum == "999");
var p = Builders<Model>.Projection.ElemMatch(x => x.doc, d => d.deliverynum == "999");
var data = Col.Find(q).Project(p).ToList();
You can also use q = Builders<Model>.Filter.Empty if you want to get all documents even if the don't contain deliverynum =``999

how to post array json .net?

i am inserting json format but need to know how i can insert in this format as mention below
{
"products": [
{
"product_id": "55",
"name": "testing data",
"price": "77",
"total": "77",
"quantity": "1",
"type": "kg"
}],
],
"totals": [
{
"code": "sub_total",
"title": "Sub-Total",
"text": "Rs277.00",
"value": "277.0000",
"sort_order": "1"
}]
}
here is my code which i am trying
items local = new items();
foreach (var item in _LocalItem){
local = new items
{
name = item.name
};
}
var json = JsonConvert.SerializeObject(local);
var request = new HttpRequestMessage(HttpMethod.Post, "http://orangepotato.rjcpacking.com/index.php?route=api/login/addcustomerOrder");
request.Content = new StringContent(json);
i dont understand where i can add "products" array in json format
Simply: don't serialize an array - serialize something that has an array in a member called products:
var json = JsonConvert.SerializeObject(new { products = local });

c# can't build json hierarchy correctly using newtonsoft

I looked at this SO question but it doesn't address my needs: Build JSON Hierarchy from Structured Data
The problem: When trying to build the json, the nesting of children isn't done correctly. The children property should contain 1 or more name array items like this:
"children": [{
"name": "XXX - Level XXX",
...instead it is generated as:
"children": []
Here's a dotnet fiddle with more code details:
I'm trying to build the tree by using json.net .Last to grab the last child and then add a JObject to that child but that isn't working out too well for me.
The main data structure used to build the json :
Dictionary<int, Industry>();
The desired json structure should be:
{
"name": "XX Level XX",
"children": [{
"name": "XXX - Level XXX",
"children": [{
"name": "XXXX - Level XXXX",
"children": [{
"name": "XXXXX - Level XXXXX",
"children": [{
"name": "XXXXXX - Level XXXXXX"
}]
}]
}]
}]
}
The actual output is:
{
"name": "XX-Level XX",
"children": [{
"name": "XXX-Level XXX",
"children": []
}, {
"name": "XXXX-Level XXXX",
"children": []
}, {
"name": "XXXXX-Level XXXXX",
"children": []
}, {
"name": "XXXXXX-Level XXXXXX",
"children": []
}
]
}
Here's the code that builds the json:
dynamic relationship = new JObject();
relationship.name = relationships[0].Industries[1].Name;
relationship.children = new JArray();
var lftIndustries = relationships[0].Industries.Where(k => k.Key > 1);
foreach (var item in lftIndustries)
{
//not good enough, need to get deepest, empty "children" node
// and add "industry" to it
var node = ((JContainer)relationship).Last;
var childArray = (JArray)((JContainer) node).Last;
var industry = new JObject(new JProperty("name", item.Value.Name), new JProperty("children", new JArray()));
childArray.Add(industry);
}
json = relationship.ToString();
I thought that using json.net .Last and .Next would be the answer.
try this in your foreach loop and tell me if it is whats youre looking for:
JToken currentContainer = null;
foreach (var item in lftIndustries)
{
//not good enough, need to get deepest, empty "children" node
// and add "industry" to it
if (currentContainer != null)
{
var node = ((JContainer)currentContainer).Last;
var childArray = (JArray)((JContainer) node).Last;
var industry = new JObject(new JProperty("name", item.Value.Name), new JProperty("children", new JArray()));
childArray.Add(industry);
currentContainer = industry;
}
else
{
var node = ((JContainer)relationship).Last;
var childArray = (JArray)((JContainer) node).Last;
var industry = new JObject(new JProperty("name", item.Value.Name), new JProperty("children", new JArray()));
childArray.Add(industry);
currentContainer = industry;
}
}
The result is this:
{
"name": "XX-Level XX",
"children": [
{
"name": "XXX-Level XXX",
"children": [
{
"name": "XXXX-Level XXXX",
"children": [
{
"name": "XXXXX-Level XXXXX",
"children": [
{
"name": "XXXXXX-Level XXXXXX",
"children": []
}
]
}
]
}
]
}
]
}
Heres the fiddle: https://dotnetfiddle.net/1yzTGU

Categories

Resources