How to serialize a dictionary to an array of json objects - c#

I have a dictionary as shown below:
var tableData = new Dictionary<string, string>();
tableData["name"] = "Sam";
tableData["city"] = "Wellington";
tableData["country"] = "New Zealand";
How can I convert the above dictionary to a serialized json data as below:
[
{ "key": "name", "val": "Sam" },
{ "key": "city", "val": "Wellington" },
{ "key": "country", "val": "New Zealand" }
]

Related

How to get all value of particular key in JSON?

I have a JSON structure that contains different levels. How to iterate the JSON and get all values of a particular key in JSON in C#
Below is my JSON file
{
"name": "EPM Company",
"id": "kpfwzgmhpm",
"type": "root",
"childern": [
{
"cid": "67",
"cname": "cname1",
"childern": [
{
"reading": [
{
"id": 121,
"name": "test1"
},
{
"id": 1121,
"name": "test11"
}
]
}
]
},
{
"cid": "454",
"cname": "cname14",
"childern": [
{
"reading": [
{
"id": 454,
"name": "test14"
},
{
"id": 21,
"name": "test141"
}
]
}
]
}
]
}
This is the JSON format. I am trying to get the value in the below format.
{
"name": "EPM Company",
"id": "kpfwzgmhpm",
"value": [
{
"id": 121,
"name": "test1",
"cid": "67",
"cname": "cname1"
},
{
"id": 1121,
"name": "test11",
"cid": "67",
"cname": "cname1"
},
{
"id": 124234,
"cname": "test12342",
"cid": "67",
"name": "cname1"
},
{
"id": 454,
"name": "test14",
"cid": "454",
"cname": "cname14"
},
{
"id": 21,
"name": "test141",
"cid": "454",
"cname": "cname14"
},
{
"id": 121,
"name": "test123122",
"cid": "454",
"cname": "cname14"
}
]
}
fetching all the reading key and its value-added to array with its cid and came. is it possible?
advanced thanks for the help
my code in c# is
public string SensorList(string entireData)
{
if (string.IsNullOrEmpty(entireData))
{
return string.Empty;
}
var returnObj = new Jobject ();
JObject o = JObject.Parse(entireData);
var childern = o["children"];
returnObj.Add("name" = o ["name"];
returnObj.Add("id" = o ["id"];
returnObj.Add("value" = o ["value"];
var valuearry = new JArray();
foreach(var data in childern)
{
foreach(var reading in data["reading"])
{
var valobj = new Jobject ();
valobj.Add( "cid",data["id"])
valobj.Add( "cname",data["name"])
valobj.Add( "name",reading["id"])
valobj.Add( "id",reading["name"])
valuearry.add()
if(data.containsKey("children"))
{
var sensorInfo = SensorList(data["children"]);
}
}
returnObj.Add("value",valuearry);
// var output = sensorInfo.SelectMany(x => ((JObject)x).Properties().Select(y => new JObject {
// new JProperty("id",y.Name),
// new JProperty("name",y.Value["name"])
// })).ToList();
// var returnArray = new JArray(output);
return returnObj.ToString();
}
}
recurring part is not working and take too much time for other long JSON file

How to create JSON object from JSON node path in C#

I want to map JSON path properties from key-value pairs to generate the JSON object in C# where the path contains nested array index path
Input:
Dictionary<string, string> properties = new Dictionary<string, string>();
properties.put("id", "1");
properties.put("name", "sample_name");
properties.put("category.id", "1");
properties.put("category.name", "sample");
properties.put("tags[0].id", "1");
properties.put("tags[0].name", "tag1");
properties.put("tags[1].id", "2");
properties.put("tags[1].name", "tag2");
properties.put("status", "available");
Output:
{
"id": 1,
"name": "sample_name",
"category": {
"id": 1,
"name": "sample"
},
"tags": [
{
"id": 1,
"name": "tag1"
},
{
"id": 2,
"name": "tag2"
}
],
"status": "available"
}
Using Jackson's JavaPropsMapper it can easily be achieved like:
JavaPropsMapper javaPropsMapper = new JavaPropsMapper();
JsonNode json = javaPropsMapper.readMapAs(properties, JsonNode.class);
How to implement this idea in C# so that I am able to generate the JSON object from the given JSON path node.
you can create anonymous object an serialize
var values = new {
id = "id",
name = "name",
category = new { id = 1, name = "sample"},
tags = new { id = 0, name = "sample" },
status = "available"
};
string json = JsonConvert.SerializeObject(values);

Recursively create JSON in C# without losing the JProperties from the first iteration

Here, I am trying to create a JSON using using Newtonsoft.Json; libraries. I came up with a function which partially does my job and when the same function is called, my previous data on the JObject is lost. I am new to this items JProperty, JObject, JArray, JToken however managed to come up with this code.
The parent is initiated in the function itself and when the function is recursively called its initiated and cleaned up again. So I added another JObject head. Making it more complicated.
string statment = "(Entity.Country = 'USA' AND Entity.ShortName = 'Adele' AND (Entity.CIFNumber = '12345' OR Statement.StatementYear = '2015'))";
public static JObject ConvertToJsonObject(string text)
{
JObject parent = new JObject();
string bracketContents = getWhatsInsideBrackets(text);
parent.Add(new JProperty("operator", ReturnOperator(text)));
parent.Add(new JProperty("rules"));
string[] operators = splitWithOperator(bracketContents);
List<JObject> req = new List<JObject>();
for (int i = 0; i < splitWithOperator(bracketContents).Length; i++)
{
if (!checkIfBracketsExists(operators[i].Trim()))
{
req.Add(GetEachCondition(operators, i));
}
else if (checkIfBracketsExists(operators[i]))
{
parent["rules"] = new JArray(ConvertToJsonObject(operators[i]));
head = parent;
parent["rules"] = (ConvertToJsonObject(operators[i]));
}
}
parent["rules"] = new JArray(req);
head["rules"] = parent;
return parent;
}
I am trying to achieve this JSON output: (Only trying to achieve the key, value of DataSetCommonQuery, dont worry about the other keys on the json)
{
"context": {
"wfId": "00000000-0000-0000-0000-000000000000",
"taskId": "00000000-0000-0000-0000-000000000000"
},
"payLoad": {
"DataSetCommonQuery": {
"operator": "AND",
"rules": [
{
"field": "ENTITY.CIFNumber",
"condition": "<>",
"value": "3123"
},
{
"field": "ENTITY.Country",
"condition": "LIKE",
"value": "USA"
},
{
"operator": "OR",
"rules": [
{
"field": "ENTITY.FYEMonth",
"condition": "=",
"value": "May"
},
{
"field": "STATEMENT.ProfitBeforeTax",
"condition": ">=",
"value": 123123
},
{
"field": "STATEMENT.NetSales",
"condition": "<=",
"value": 234234
},
{
"field": "STATEMENT.statementdatekey_",
"condition": "=",
"value": "2019-07-01 12:00:00"
}
]
}
]
},
"PeerType": "DEFAULT",
"Name": "API TEST",
"Description": "API TEST",
"BmkPeerFormatId": "DBBmk",
"OperationType": "Create"
}
}

How to return this format this JSON into an array of strings

I am executing a linq query which gets me all the records from a table:
var data = _context.People.ToList(); //_context is my DataContext.
The above returns the the value:
{
"name": "john",
"age": "30"
},
{
"name": "jane",
"age": "31"
}
but according to jsonlint, this is invalid and I need to have it be returned as:
[{
"name": "john",
"age": "30"
},
{
"name": "jane",
"age": "31"
}]
How can I do this?
viewData.xldata = [];
$.each(data, function(i, row) {
var strRow = JSON.stringify(row);
viewData.xldata.push(strRow);});
Deserialize using `JavaScriptSerializer:
var people = jss.Deserialize<List<People>>(args["xldata"]);
Try this:
List<People> data= _context.People.ToList();
System.Web.Script.Serialization.JavaScriptSerializer objSerializer = default(System.Web.Script.Serialization.JavaScriptSerializer);
objSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return objSerializer.Serialize(data);

Deserialize GET response

How do I deserialize this text. I tried with JSON but I get "Invalid JSON primitive" error.
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 1
},
"objects": [
{
"blocked": false,
"groups": [],
"id": "1111",
"name": "John Doe",
"number": "+15555555555",
"resource_uri": "/api/v1/contacts/1111/"
}
]
}
This is the code I used:
var jss = new JavaScriptSerializer();
var dictionary = jss.Deserialize<Dictionary<string, string>>(buffer.ToString());
Easy to Fix. Deserialize to <Dictionary<string, object> instead of <Dictionary<string, string>
var dictionary = jss.Deserialize<Dictionary<string, object>>(buffer.ToString());
Full test code
string json = #"{
""meta"": {
""limit"": 20,
""next"": null,
""offset"": 0,
""previous"": null,
""total_count"": 1
},
""objects"": [
{
""blocked"": false,
""groups"": [],
""id"": ""1111"",
""name"": ""John Doe"",
""number"": ""+15555555555"",
""resource_uri"": ""/api/v1/contacts/1111/""
}
]
}";
var jss = new JavaScriptSerializer();
var dictionary = jss.Deserialize<Dictionary<string, object>>(json);

Categories