JSON Enum list deserialization - c#

I have JSON Like below
{
"_id": "0FEB6D4B-8DA5-4143-B926-11A7AE4F3B12",
"device": {
"name": "test",
"family": "test"
},
"channels": [
{
"mcl": 33,
"vtype": "FLOAT",
"category": " Current"
},
{
"tag": "OperationMode",
"vtype": "BYTE",
"enums": [
{
"0": "Off"
},
{
"1": "On"
},
{
"2": "ByPass"
}
]
}
]
}
I am using Json.net to deserialize the JSON to C# object. I am not able to manage to convert the enum list. I validated if this is valid JSON. I tried with custom converter & string converter but reader value is null. Any quick help appreciated.

JObject jR = JObject.Parse(YourJsonString);
JArray oR = (JArray)jR["channels"];
JArray jA = (JArray)oR[1]["enums"];
foreach (var item in jA)
{
Dictionary<string,string> enums = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>>(item.ToString());
foreach (var en in enums)
{
Console.WriteLine(en.Value);
}
}
Fiddler: https://dotnetfiddle.net/ziSep1

Related

ChoETL json to csv with multiple arrays

If I have a sample json like this and I want to use choETL to convert json to csv, how do i write both arrays to one file?
{
"Id": "123456",
"Request": [
{
"firstName": "A",
"lastName": "B",
}
],
"Response": [
{
"SId": "123"
}
]
}
Csv file should be something like
Id,firstName,lastName,SId
123456,A,B,123
Here is how you can produce the expected CSV from the json by using ChoETL
using (var r = ChoJSONReader.LoadText(json)
.WithField("Id")
.WithField("firstName", jsonPath:"Request[0].firstName", isArray:false)
.WithField("lastName", jsonPath:"Request[0].lastName", isArray:false)
.WithField("SId", jsonPath:"Response[0].SId", isArray:false)
)
{
using (var w = new ChoCSVWriter(Console.Out).WithFirstLineHeader())
w.Write(r);
}
Output:
Id,firstName,lastName,SId
123456,A,B,123
Sample fiddle: https://dotnetfiddle.net/CnBX3C
UPDATE:
If the array is dynamic, here is one way to produce the CSV output by Request json array field
Sample JSON:
{
"Id": "123456",
"Request": [
{
"firstName": "A",
"lastName": "B",
},
{
"firstName": "A1",
"lastName": "B1",
}
],
"Response": [
{
"SId": "123"
},
{
"SId": "1234"
}
]
}
Here is the code to parse the json by Request json array field
using (var r = ChoJSONReader.LoadText(json)
.Configure(c => c.FlattenNode = true).Configure(c => c.FlattenByNodeName = "Request")
)
{
using (var w = new ChoCSVWriter(Console.Out).WithFirstLineHeader())
w.Write(r);
}
Output:
Id,Response_0_SId,Response_1_SId,RequestfirstName,RequestlastName
123456,123,1234,A,B
123456,123,1234,A1,B
Sample fiddle: https://dotnetfiddle.net/CnBX3C

how to replace property values in a dynamic JSON?

I'm reading my json file from and trying to replace the property values. JSON file is below.
{
"fields": {
"summary": "summaryValue",
"project": {
"key": "projectValue"
},
"priority": {
"name": "priorityValue"
},
"Requestor": {
"name": "RequestorValue"
},
"issue": {
"name": "issueValue"
},
"labels": "LabelValue",
"customfield_xyz": "customfield_xyzValue"
}
}
How can I replace the value for each item inside the fields property ?
for ex:
{"fields": {
"summary": "NewsummaryValue",
"project": {
"key": "NewprojectValue"
},
"priority": {
"name": "NewpriorityValue"
}
}
}
Below is the code to parse my json file,
StreamReader r = new StreamReader(filepath);
var jsondata = r.ReadToEnd();
var jobj = JObject.Parse(jsondata);
foreach (var item in jobj.Properties())
{
\\replace code
}
I do not know exactly what you want. But I changed the json information in the code snippet as you wanted.
dynamic dataCollection = JsonConvert.DeserializeObject<dynamic>(jsonData);
string summary = dataCollection["fields"]["summary"];
string project = dataCollection["fields"]["project"]["key"];
string priority = dataCollection["fields"]["priority"]["name"];
dynamic json = new JObject();
json.summary = summary;
json.project = project;
json.priority = priority;
dynamic jsonRoot = new JObject();
jsonRoot.fields = json;
Console.WriteLine(jsonRoot.ToString());
output:

Get JSON child element value

I'm trying to get spuCode from this JSON:
{
"msg": "success",
"state": 0,
"data": {
"result": {
"spuCode": "541426110605",
"productName": "纯黑色斜纹面料铅笔裤百搭大码小脚裤弹力打底裤休闲裤子女",
"productTitle": null,
"spuImgs": [
"https://cbu01.alicdn.com/img/ibank/2016/276/468/3618864672_1742354982.jpg",
"https://cbu01.alicdn.com/img/ibank/2016/793/372/3617273397_1742354982.jpg",
"https://cbu01.alicdn.com/img/ibank/2016/726/552/3617255627_1742354982.jpg",
"https://cbu01.alicdn.com/img/ibank/2017/521/101/4624101125_1742354982.jpg",
"https://cbu01.alicdn.com/img/ibank/2017/070/749/4580947070_1742354982.jpg"
],
"upAndDown": 1,
"updateTime": 1537096913958,
"platform": "ALIBABA",
"skus": [
{
"skuCode": "3488434133172",
"sellPrice": 3900,
"sellableNum": 905,
"productProps": [
{
"propId": 7590793702270582000,
"valueId": 5453504708925905000,
"propName": "颜色",
"valueName": "纯黑色(相同面料)"
},
{
"propId": 9000005669393888000,
"valueId": 6217370164147047000,
"propName": "尺码",
"valueName": "XXL"
}
],
As you can see there is Parent data with child result so I added this code:
string sp = "";
var obj = Newtonsoft.Json.Linq.JObject.Parse(responseFromServer);
foreach (JObject child in obj["data"]["result"].OfType<JObject>())
{
sp = child["spuCode"].ToString();
MessageBox.Show(sp);
}
But it never triggers MessageBox.Show what am I missing here?
result isn't an array so there is no need for foreach.
Try SelectToken method like this:
var spuCode = (string)obj.SelectToken("data.result.spuCode");

How can I add values to a NewtonSoft JObect?

I am usin NewtonSoft JSON.Net and I have a JObject that I need to add and remove items to and form it dynamicly from my code.
If this is my json:
{
"IgnoredInterests": [
{
"Id": 1,
"Name": "test"
},
{
"Id": 2,
"Name": "test"
}
]
}
I need to be able to add more items or even remove items from it via code.
How can I add this to the JObject:
{
"Id": 3,
"Name": "test"
}
And even remove:
{
"Id": 2,
"Name": "test"
}
I appreciate your help...
string json = #"{
'IgnoredInterests': [
{
'Id': 1,
'Name': 'test'
},
{
'Id': 2,
'Name': 'test'
}
]
}";
JObject obj = JObject.Parse(json);
string json_add = #"{
'Id': 3,
'Name': 'test'
}";
JArray array = obj.GetValue("IgnoredInterests") as JArray;
JObject obj_add = JObject.Parse(json_add);
array.Add(obj_add);
foreach (JObject item in array.Children())
{
if (item.GetValue("Id").ToString() == "2")
{
array.Remove(item);
break;
}
}

How do i add $ref to a JSONSchema?

I have a JSONSchema which will have some items . Now the schema/s that define those items need to be referred in the main schema ?
* one schema that you reference:
{
"id": "http://some.where/sub/schema#",
"type": "object",
"properties": {
"p1": {
"type": "integer",
"minimum": 12
}
}
}
--- * the main schema: ----
{
"id": "http://path.to/base/schema#",
"type": "array",
"items": {
"extends": {
"$ref": "http://some.where/sub/schema#/properties/p1"
},
"divisibleBy": 5
}
}
Also note , i will have multiple items in the item . I do not see a way of doing this in the api . Nor does the api allow me to add custom properties . How can i achieve this ? I am using JSON.net.
Since It will be too long for a comment, I'll post it as an answer. But You should work on it to customize according to your needs.
string oneSchema = #"{
""id"": ""http://some.where/sub/schema#"",
""type"": ""object"",
""properties"": {
""p1"": {
""type"": ""integer"",
""minimum"": 12
}
}
} ";
string main = #"
{
""id"": ""http://path.to/base/schema#"",
""type"": ""array"",
""items"": {
""extends"": {
""$ref"": ""http://some.where/sub/schema#/properties/p1""
},
""divisibleBy"": 5
}
}";
var JObjMain = (JObject)JsonConvert.DeserializeObject(main);
var jObjOther = (JObject)JsonConvert.DeserializeObject(oneSchema);
JToken src = JObjMain["items"]["extends"]["$ref"];
JToken reference = jObjOther["id"];
var path = src.ToString().Replace(reference.ToString(), "").Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
JToken j = jObjOther[path[0]];
for(int i=1;i<path.Length;i++)
{
j = j[path[i]];
}
src.Replace(j);
Console.WriteLine(JObjMain);

Categories