Form the JSON object - serialization C# - c#

"fields": [
{
"field": {
"name": "SMS",
"value": "Yes"
}
},
{
"field": {
"name": "Email",
"value": ""
}
},
{
"field": {
"name": "Total",
"value": ""
}
},
]
I have tried to form the JSON format like above, so i formed the class like below. While serialization it does not return expected form, how can i achieve this one.
public class Test
{
public List<Field> fields;
}
public class Field
{
public string name { get; set; }
public string value { get; set; }
}
Response:
"fields": [{
"name": "SMS",
"value": "Yes"
}, {
"name": "Email",
"value": ""
},{
"name": "Total",
"value": ""
}]

Use this website http://json2csharp.com and generate all the classes automatically. Just copy-paste your json there.

You can customize resulting JSON object with anonymous types and LINQ. Please try this code:
var test = new Test {fields = new List<Field>()};
test.fields.Add(new Field {name = "f1", value = "v1"});
test.fields.Add(new Field {name = "f2", value = "v2"});
var json = JObject.FromObject(new { fields = test.fields.Select(f => new {field = f}).ToArray() })
.ToString();
A json variable would be:
{
"fields": [
{
"field": {
"name": "f1",
"value": "v1"
}
},
{
"field": {
"name": "f2",
"value": "v2"
}
}
]
}

You just missed a class level:
public class Test
{
public List<FieldHolder> fields;
}
public class FieldHolder
{
public Field field { get; set; }
}
public class Field
{
public string name { get; set; }
public string value { get; set; }
}

Related

How can I deserialize Array of Arrays in Newtonsoft Json C#? [duplicate]

I have this JSON:
[
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 1",
"Values": [
"Acc 1"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "1",
"Values": [
"1"
]
}
}
],
"Name": "account",
"Id": "1"
},
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 2",
"Values": [
"Acc 2"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "2",
"Values": [
"2"
]
}
}
],
"Name": "account",
"Id": "2"
},
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 3",
"Values": [
"Acc 3"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "3",
"Values": [
"3"
]
}
}
],
"Name": "account",
"Id": "2"
}
]
And I have these classes:
public class RetrieveMultipleResponse
{
public List<Attribute> Attributes { get; set; }
public string Name { get; set; }
public string Id { get; set; }
}
public class Value
{
[JsonProperty("Value")]
public string value { get; set; }
public List<string> Values { get; set; }
}
public class Attribute
{
public string Key { get; set; }
public Value Value { get; set; }
}
I am trying to deserialize the above JSON using the code below:
var objResponse1 = JsonConvert.DeserializeObject<RetrieveMultipleResponse>(JsonStr);
but I am getting this error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'test.Model.RetrieveMultipleResponse' because the type requires a JSON
object (e.g. {"name":"value"}) to deserialize correctly. To fix this
error either change the JSON to a JSON object (e.g. {"name":"value"})
or change the deserialized type to an array or a type that implements
a collection interface (e.g. ICollection, IList) like List that can
be deserialized from a JSON array. JsonArrayAttribute can also be
added to the type to force it to deserialize from a JSON array. Path
'', line 1, position 1.
Your json string is wrapped within square brackets ([]), hence it is interpreted as array instead of single RetrieveMultipleResponse object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse, for example :
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
If one wants to support Generics (in an extension method) this is the pattern...
public static List<T> Deserialize<T>(this string SerializedJSONString)
{
var stuff = JsonConvert.DeserializeObject<List<T>>(SerializedJSONString);
return stuff;
}
It is used like this:
var rc = new MyHttpClient(URL);
//This response is the JSON Array (see posts above)
var response = rc.SendRequest();
var data = response.Deserialize<MyClassType>();
MyClassType looks like this (must match name value pairs of JSON array)
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class MyClassType
{
[JsonProperty(PropertyName = "Id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "Name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "Description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "Manager")]
public string Manager { get; set; }
[JsonProperty(PropertyName = "LastUpdate")]
public DateTime LastUpdate { get; set; }
}
Use NUGET to download Newtonsoft.Json add a reference where needed...
using Newtonsoft.Json;
Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:
var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass));
return des.data.Count.ToString();
Deserializing JSON array into strongly typed .NET object
Use this, FrontData is JSON string:
var objResponse1 = JsonConvert.DeserializeObject<List<DataTransfer>>(FrontData);
and extract list:
var a = objResponse1[0];
var b = a.CustomerData;
To extract the first element (Key) try this method and it will be the same for the others :
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("Your URL"))
{
var apiResponse = await response.Content.ReadAsStringAsync();
var list = JObject.Parse(apiResponse)["Attributes"].Select(el => new { Key= (string)el["Key"] }).ToList();
var Keys= list.Select(p => p.Key).ToList();
}
}
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
worked!

Get nested fieldNames from JSON object

I have a JSON that contains a list of types. These types have some name and some fields.
Fields have a property of dataType and if it's value is object, it refers to a another type. That type could be found by its name specified in referenceType property.
There is also a property named parentType which means the type is a child of the parentType and it contains some additional properties, but have to be considered as an object of parentType only.
I am trying to process this JSON to get all the nested property names for all the types present in the array.
{
"types": [
{
"name": "User1",
"fields": [
{
"name": "name",
"dataType": "string"
},
{
"name": "address",
"dataType": "object",
"referenceType": "Address",
"isArray": true
},
{
"name": "weeklyRoles",
"dataType": "object",
"isArray": true,
"referenceType": "Role"
}
]
},
{
"name": "User2",
"fields": [
{
"name": "name",
"dataType": "string"
},
{
"name": "address",
"dataType": "object",
"referenceType": "Address",
"isArray": true
}
]
},
{
"name": "Address",
"fields": [
{
"name": "AddressLine1",
"dataType": "string"
},
{
"name": "AddressLine2",
"dataType": "string"
}
]
},
{
"name": "BusinessAddress",
"parentType": "Address",
"fields": [
{
"name": "headquarters",
"dataType": "string"
}
]
},
{
"name": "ServiceAddress",
"parentType": "Address",
"fields": [
{
"name": "servicePartner",
"dataType": "string"
},
{
"name": "serviceType",
"dataType": "string"
}
]
},
{
"name": "Role",
"fields": [
{
"name": "roleName",
"dataType": "string"
},
{
"name": "accessCountsObj1",
"dataType": "object",
"referenceType": "Role2"
}
]
},
{
"name": "Role2",
"fields": [
{
"name": "roleName2",
"dataType": "string"
},
{
"name": "accessCountsObj2",
"dataType": "object",
"referenceType": "Role3"
}
]
},
{
"name": "Role3",
"fields": [
{
"name": "roleName3",
"dataType": "string"
},
{
"name": "accessCountsObj3",
"dataType": "object",
"referenceType": "Role4"
}
]
},
{
"name": "Role4",
"fields": [
{
"name": "roleName4",
"dataType": "string"
}
]
}
]
}
Pattern in which I am expecting the result is <typeName>;<fieldName>.<nestedFieldName>
Expected Output
[
"User1;address.AddressLine1",
"User1;address.AddressLine2",
"User1;address.headquarters",
"User1;address.servicePartner",
"User1;address.serviceType",
"User1;weeklyRoles.roleName",
"User1;weeklyRoles.accessCountsObj1.roleName2",
"User1;weeklyRoles.accessCountsObj1.accessCountsObj2.roleName3",
"User1;weeklyRoles.accessCountsObj1.accessCountsObj2.accessCountsObj3.roleName4",
"User2;address.AddressLine1",
"User2;address.AddressLine2",
"User2;address.headquarters",
"User2;address.servicePartner",
"User2;address.serviceType",
"Role;accessCountsObj1.roleName2",
"Role;accessCountsObj1.accessCountsObj2.roleName3",
"Role;accessCountsObj1.accessCountsObj2.accessCountsObj3.roleName4",
"Role2;accessCountsObj2.roleName3",
"Role2;accessCountsObj2.accessCountsObj3.roleName4",
]
I have tried to write a recursive function to process it but it is not giving me the expected result and also does not have terminating condition.
public IList<string> GetKeys(JArray types, string parentType = null)
{
var nestedKeys = new List<string>();
foreach (var type in types)
{
var fields = type[Constants.Fields].ToObject<List<JObject>>();
var typeName = type.Value<string>("name");
var nestedKeyBuilder = new StringBuilder($"{typeName};");
if (!string.IsNullOrEmpty(parentType))
{
nestedKeyBuilder = new StringBuilder($"{parentType};");
}
foreach (var field in fields)
{
var datatype = field.Value<string>("dataType");
if (string.Equals(datatype,"object"))
{
var fieldName = field.Value<string>("name");
var referenceTypeName = field.Value<string>("referenceType");
var referenceTypeObject = types.Where(t => string.Equals(t.Value<string>("name"), referenceTypeName))?.First();
if (referenceTypeObject != null)
{
var refTypeFields = referenceTypeObject["fields"].ToObject<List<JObject>>();
foreach (var refTypeField in refTypeFields)
{
var refTypeFieldName = refTypeField.Value<string>("name");
var refTypeDataType = refTypeField.Value<string>("dataType");
var refTypeReferenceTypeName = refTypeField.Value<string>("referenceType");
if (string.Equals(refTypeDataType, "object") && string.Equals(refTypeReferenceTypeName, currentReferenceType))
{
var refTypeNestedKeys = GetKeys(types, typeName);
nestedKeys.AddRange(refTypeNestedKeys);
}
else
{
nestedKeyBuilder.Append($"{fieldName}.{refTypeFieldName}");
nestedKeys.Add(nestedKeyBuilder.ToString());
}
}
}
}
}
}
return nestedKeys;
}
There is a NuGet that you can use to handle JSON files.
Search for Newtonsoft.Json
https://www.newtonsoft.com/json
All your problems should be solved with that
You can use Newtonsoft library to do this.
This is your POCO class.
{
public string name { get; set; }
public string dataType { get; set; }
public string referenceType { get; set; }
public bool? isArray { get; set; }
}
public class Type
{
public string name { get; set; }
public List<Field> fields { get; set; }
public string parentType { get; set; }
}
public class RootObject
{
public List<Type> types { get; set; }
}
and write the function to DeserializeObject
[TestMethod]
public void Read()
{
var sample1 = #"X:\JsonFilePath\data.json";
var jsonString=File.ReadAllText(sample1);
var result =JsonConvert.DeserializeObject<RootObject>(jsonString);
Assert.IsNotNull(result);
}
Use newtonsoft JSON to Deseriliaze the JSON string.
JSON.Deserialize<IEnumerable<Type>>(jsonString);
This should give you an IEnumerable to process it however you want. Types is the class you create with the JSON properties as class properties. You can use something like this
NOTE: Type and Field are very vague names. Type is a c# class and therefore you should not use it to create a class of your own. You will face ambiguous errors and you will need to qualify the namespace in full to use your class. Strongly suggesting to name it something else and use the attributes to map it to the JSON string.
[JsonObject(Title="People")]
public class Type
{
[JsonProperty("name")]
string Name{ get; set; }
[JsonProperty("fields")]
Field FieldValue[]{ get; set; }
}

How to deserialise JSON from HubSpot

I am having trouble deserializing JSON received from HubSpot ContactList API.
I am using Restsharp and NewtonSoft, and I'm having real struggles understanding how to correctly define the required classes in order to deserialize the JSON string, which is below:
"contacts": [
{
"vid": 2251,
"portal-id": 5532227,
"is-contact": true,
"profile-url": "https://app.hubspot.com/contacts/5532227/contact/2251",
"properties": {
"firstname": {
"value": "Carl"
},
"lastmodifieddate": {
"value": "1554898386040"
},
"company": {
"value": "Cygnus Project"
},
"lastname": {
"value": "Swann"
}
},
"form-submissions": [],
"identity-profiles": [
{
"vid": 2251,
"saved-at-timestamp": 1553635648634,
"deleted-changed-timestamp": 0,
"identities": [
{
"type": "EMAIL",
"value": "cswann#cygnus.co.uk",
"timestamp": 1553635648591,
"is-primary": true
},
{
"type": "LEAD_GUID",
"value": "e2345",
"timestamp": 1553635648630
}
]
}
],
"merge-audits": []
},
{
"vid": 2301,
"portal-id": 5532227,
"is-contact": true,
"profile-url": "https://app.hubspot.com/contacts/5532227/contact/2301",
"properties": {
"firstname": {
"value": "Carlos"
},
"lastmodifieddate": {
"value": "1554886333954"
},
"company": {
"value": "Khaos Control"
},
"lastname": {
"value": "Swannington"
}
},
"identity-profiles": [
{
"vid": 2301,
"saved-at-timestamp": 1553635648733,
"deleted-changed-timestamp": 0,
"identities": [
{
"type": "EMAIL",
"value": "cswann#khaoscontrol.com",
"timestamp": 1553635648578,
"is-primary": true
},
{
"type": "LEAD_GUID",
"value": "c7f403ba",
"timestamp": 1553635648729
}
]
}
],
"merge-audits": []
}
],
"has-more": false,
"vid-offset": 2401
}
If I simply request the vid, I correctly get 2 vid's back. It's when I try to do the properties and that i get a fail.
Please help
Lets reduce the Json to the minimum to reproduce your error :
{
"vid": 2301,
"portal-id": 5532227,
"is-contact": true,
"profile-url": "https://app.hubspot.com/contacts/5532227/contact/2301",
"properties": {
"firstname": {
"value": "Carlos"
},
"lastmodifieddate": {
"value": "1554886333954"
},
"company": {
"value": "Khaos Control"
},
"lastname": {
"value": "Swannington"
}
}
}
And the appropriate class ContactListAPI_Result:
public partial class ContactListAPI_Result
{
[JsonProperty("vid")]
public long Vid { get; set; }
[JsonProperty("portal-id")]
public long PortalId { get; set; }
[JsonProperty("is-contact")]
public bool IsContact { get; set; }
[JsonProperty("profile-url")]
public Uri ProfileUrl { get; set; }
[JsonProperty("properties")]
public Dictionary<string, Dictionary<string, string>> Properties { get; set; }
}
public partial class ContactListAPI_Result
{
public static ContactListAPI_Result FromJson(string json)
=> JsonConvert.DeserializeObject<ContactListAPI_Result>(json);
//public static ContactListAPI_Result FromJson(string json)
// => JsonConvert.DeserializeObject<ContactListAPI_Result>(json, Converter.Settings);
}
public static void toto()
{
string input = #" {
""vid"": 2301,
""portal-id"": 5532227,
""is-contact"": true,
""profile-url"": ""https://app.hubspot.com/contacts/5532227/contact/2301"",
""properties"": {
""firstname"": {
""value"": ""Carlos""
},
""lastmodifieddate"": {
""value"": ""1554886333954""
},
""company"": {
""value"": ""Khaos Control""
},
""lastname"": {
""value"": ""Swannington""
}
}
}";
var foo = ContactListAPI_Result.FromJson(input);
}
But the Value of one property will be burrow in the sub dictionary, we can the project the object in a more usefull one :
public partial class ItemDTO
{
public long Vid { get; set; }
public long PortalId { get; set; }
public bool IsContact { get; set; }
public Uri ProfileUrl { get; set; }
public Dictionary<string, string> Properties { get; set; }
}
Adding the projection to the Class:
public ItemDTO ToDTO()
{
return new ItemDTO
{
Vid = Vid,
PortalId = PortalId,
IsContact = IsContact,
ProfileUrl = ProfileUrl,
Properties =
Properties.ToDictionary(
p => p.Key,
p => p.Value["value"]
)
};
}
Usage :
var result = foo.ToDTO();
Live Demo
Creating and managing class structure for big and nested key/value pair json is tedious task
So one approach is to use JToken instead.
You can simply parse your JSON to JToken and by querying parsed object, you will easily read the data that you want without creating class structure for your json
From your post it seems you need to retrieve vid and properties from your json so try below code,
string json = "Your json here";
JToken jToken = JToken.Parse(json);
var result = jToken["contacts"].ToObject<JArray>()
.Select(x => new
{
vid = Convert.ToInt32(x["vid"]),
properties = x["properties"].ToObject<Dictionary<string, JToken>>()
.Select(y => new
{
Key = y.Key,
Value = y.Value["value"].ToString()
}).ToList()
}).ToList();
//-----------Print the result to console------------
foreach (var item in result)
{
Console.WriteLine(item.vid);
foreach (var prop in item.properties)
{
Console.WriteLine(prop.Key + " - " + prop.Value);
}
Console.WriteLine();
}
Output:

UWP create list using JSON data

OK. I have sent a GET request to SharePoint and received a string back:
"{\"#odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items\",\"value\":[{\"#odata.etag\":\"\\\"a69b1840-239d-42ed-9b20-8789761fb06a,3\\\"\",\"createdDateTime\":\"2018-08-25T22:44:16Z\",\"eTag\":\"\\\"a69b1840-239d-42ed-9b20-8789761fb06a,3\\\"\",\"id\":\"9\",\"lastModifiedDateTime\":\"2018-08-25T22:44:16Z\",\"webUrl\":\"https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/9_.000\",\"createdBy\":{\"user\":{\"email\":\"XXXXX#XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"lastModifiedBy\":{\"user\":{\"email\":\"XXXXX#XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"parentReference\":{},\"contentType\":{\"id\":\"0x0100E19591A4ECA81542AEA41A6AAFED6781\"},\"fields#odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('9')/fields/$entity\",\"fields\":{\"#odata.etag\":\"\\\"a69b1840-239d-42ed-9b20-8789761fb06a,3\\\"\",\"SerialNumber\":\"20180824-1353-DC6-Generator-A\",\"id\":\"9\"}},{\"#odata.etag\":\"\\\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\\\"\",\"createdDateTime\":\"2018-08-25T22:45:55Z\",\"eTag\":\"\\\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\\\"\",\"id\":\"10\",\"lastModifiedDateTime\":\"2018-08-25T22:45:55Z\",\"webUrl\":\"https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/10_.000\",\"createdBy\":{\"user\":{\"email\":\"XXXXX#XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"lastModifiedBy\":{\"user\":{\"email\":\"XXXXX#XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"parentReference\":{},\"contentType\":{\"id\":\"0x0100E19591A4ECA81542AEA41A6AAFED6781\"},\"fields#odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('10')/fields/$entity\",\"fields\":{\"#odata.etag\":\"\\\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\\\"\",\"SerialNumber\":\"20180824-1416-DC6-Generator-B\",\"id\":\"10\"}},{\"#odata.etag\":\"\\\"00024848-0d4e-4ee8-b018-f1653af2a577,3\\\"\",\"createdDateTime\":\"2018-08-25T22:47:30Z\",\"eTag\":\"\\\"00024848-0d4e-4ee8-b018-f1653af2a577,3\\\"\",\"id\":\"11\",\"lastModifiedDateTime\":\"2018-08-25T22:47:30Z\",\"webUrl\":\"https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/11_.000\",\"createdBy\":{\"user\":{\"email\":\"XXXXX#XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"lastModifiedBy\":{\"user\":{\"email\":\"XXXXX#XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"parentReference\":{},\"contentType\":{\"id\":\"0x0100E19591A4ECA81542AEA41A6AAFED6781\"},\"fields#odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('11')/fields/$entity\",\"fields\":{\"#odata.etag\":\"\\\"00024848-0d4e-4ee8-b018-f1653af2a577,3\\\"\",\"SerialNumber\":\"20180824-1438-DC6-Generator-R\",\"id\":\"11\"}},{\"#odata.etag\":\"\\\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\\\"\",\"createdDateTime\":\"2018-08-25T23:02:43Z\",\"eTag\":\"\\\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\\\"\",\"id\":\"12\",\"lastModifiedDateTime\":\"2018-08-25T23:02:43Z\",\"webUrl\":\"https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/12_.000\",\"createdBy\":{\"user\":{\"email\":\"XXXXX#XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"lastModifiedBy\":{\"user\":{\"email\":\"XXXXX#XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"parentReference\":{},\"contentType\":{\"id\":\"0x0100E19591A4ECA81542AEA41A6AAFED6781\"},\"fields#odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('12')/fields/$entity\",\"fields\":{\"#odata.etag\":\"\\\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\\\"\",\"SerialNumber\":\"20180824-1456-DC6-Generator-C\",\"id\":\"12\"}}]}"
Which will JObject.Parse to this:
{{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items",
"value": [
{
"#odata.etag": "\"a69b1840-239d-42ed-9b20-8789761fb06a,3\"",
"createdDateTime": "2018-08-25T22:44:16Z",
"eTag": "\"a69b1840-239d-42ed-9b20-8789761fb06a,3\"",
"id": "9",
"lastModifiedDateTime": "2018-08-25T22:44:16Z",
"webUrl": "https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/9_.000",
"createdBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"lastModifiedBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"parentReference": {},
"contentType": {
"id": "0x0100E19591A4ECA81542AEA41A6AAFED6781"
},
"fields#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('9')/fields/$entity",
"fields": {
"#odata.etag": "\"a69b1840-239d-42ed-9b20-8789761fb06a,3\"",
"SerialNumber": "20180824-1353-DC6-Generator-A",
"id": "9"
}
},
{
"#odata.etag": "\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\"",
"createdDateTime": "2018-08-25T22:45:55Z",
"eTag": "\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\"",
"id": "10",
"lastModifiedDateTime": "2018-08-25T22:45:55Z",
"webUrl": "https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/10_.000",
"createdBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"lastModifiedBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"parentReference": {},
"contentType": {
"id": "0x0100E19591A4ECA81542AEA41A6AAFED6781"
},
"fields#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('10')/fields/$entity",
"fields": {
"#odata.etag": "\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\"",
"SerialNumber": "20180824-1416-DC6-Generator-B",
"id": "10"
}
},
{
"#odata.etag": "\"00024848-0d4e-4ee8-b018-f1653af2a577,3\"",
"createdDateTime": "2018-08-25T22:47:30Z",
"eTag": "\"00024848-0d4e-4ee8-b018-f1653af2a577,3\"",
"id": "11",
"lastModifiedDateTime": "2018-08-25T22:47:30Z",
"webUrl": "https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/11_.000",
"createdBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"lastModifiedBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"parentReference": {},
"contentType": {
"id": "0x0100E19591A4ECA81542AEA41A6AAFED6781"
},
"fields#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('11')/fields/$entity",
"fields": {
"#odata.etag": "\"00024848-0d4e-4ee8-b018-f1653af2a577,3\"",
"SerialNumber": "20180824-1438-DC6-Generator-R",
"id": "11"
}
},
{
"#odata.etag": "\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\"",
"createdDateTime": "2018-08-25T23:02:43Z",
"eTag": "\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\"",
"id": "12",
"lastModifiedDateTime": "2018-08-25T23:02:43Z",
"webUrl": "https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/12_.000",
"createdBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"lastModifiedBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"parentReference": {},
"contentType": {
"id": "0x0100E19591A4ECA81542AEA41A6AAFED6781"
},
"fields#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('12')/fields/$entity",
"fields": {
"#odata.etag": "\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\"",
"SerialNumber": "20180824-1456-DC6-Generator-C",
"id": "12"
}
}
]
}}
What I ultimately want to do is create a dropdown that is populated with the SerialNumber. When the SerialNumber is selected in the dropdown, it will return the id so that I can then plug that into a GET request to retrieve the appropriate listitems.
I am trying to figure out if I need to do a foreach to create a LIST<> or something else all together.
I do have this class setup, but wasn't sure if I could use it the way I thought I could.
public class Lookup
{
string id { get; set; };
string SerialNumber { get; set; }
}
This is the final working code:
private async void GetButton_Click(object sender, RoutedEventArgs e)
{
var (authResult, message) = await Authentication.AquireTokenAsync();
ResultText.Text = message;
if (authResult != null)
{
var httpClient = new HttpClient();
HttpResponseMessage response;
var request = new HttpRequestMessage(HttpMethod.Get, geturl);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
response = await httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(content);
var result = JsonConvert.DeserializeObject<SharePointListItems.RootObject>(content);
foreach (var d in result.value)
{
Lookups.Add(new SharePointListItems.Lookup() { id = d.fields.id, SerialNumber = d.fields.SerialNumber });
}
TestComboBox.ItemsSource = Lookups;
}
}
private void TestComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (TestComboBox.SelectedIndex != -1)
{
var mylookupId = (TestComboBox.SelectedItem as SharePointListItems.Lookup).id;// get your id and do further processing here.
ResultText.Text = mylookupId;
}
}
public class SharePointListItems
{
public class Lookup
{
public string SerialNumber { get; set; }
public string id { get; set; }
public override string ToString()
{
return SerialNumber;
}
}
public class Value
{
public Lookup fields { get; set; }
}
public class Fields
{
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
...
}
public class RootObject
{
[JsonProperty("#odata.context")]
public string ODataContext { get; set; }
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
[JsonProperty("fields#odata.context")]
public string FieldsODataContext { get; set; }
public Fields Fields { get; set; }
public List<Value> value { get; set; }
}
}
There are two way can create model easily.
You can use Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class, you can easier to know the relation between Json and model.
If you can't use Web Essentials you can instead of use http://json2csharp.com/ online JSON to Model class.
You can try to use those models to carry your JSON Format.
public class Lookup
{
public string SerialNumber { get; set; }
public string id { get; set; }
}
public class Value
{
public Lookup fields { get; set; }
}
public class RootObject
{
public List<Value> value { get; set; }
}
Then you can use obj.value property collection directly.
var obj = JsonConvert.DeserializeObject<RootObject>(jsonData);
foreach (var item in obj.value)
{
//item.fields.id
//item.fields.SerialNumber
}
A good example of how to bind a list of data to Combobox ( dropdown ) is here : https://www.c-sharpcorner.com/article/data-binding-in-xaml-uwp-using-combobox/
in this example the class is a Student with id and Name and it shows how u can show the name in combobox.
I will modify it a little for your scenario but if you want to go in depth than you can visit the provided link above.
This is the class
public class Fields
{
public string SerialNumber { get; set; }
public string id { get; set; }
public override string ToString()
{
return this.SerialNumber; // so that we can just bind to the object and get serial number in the ui.
}
}
Backend for adding items to the List
public sealed partial class MainPage: Page
{
List<Lookup> Lookups = new List<Lookup>();
public MainPage()
{
this.InitializeComponent();
Lookups.Add(new Lookup() {id = 1, SerialNumber = "S1"});
Lookups.Add(new Lookup() {id = 2, SerialNumber = "S2"});
Lookups.Add(new Lookup() {id = 3, SerialNumber = "S3"});
Lookups.Add(new Lookup() {id = 4, SerialNumber = "S4"});
//add as many items here as u want, u can even use a for loop or foreach loop or a Deserializer with newsoft json to get objects from ur json like below.
//var data = JsonConvert.DeserializeObject<RootObject>(jsonData);
//foreach (var d in data.value)
//{
// //d.fields.id //this is how u can get the inside properties.
//}
yourComboBox.ItemSource = Lookups;//setting item source to UI.
}
}
after you successfully bind the data with UI you can use SelectionChanged event of your combobox to do further logic as you require,
void MyComboBox_SelectionChanged(object sender, object args)
{
if(MyCombobox.SelectedIndex!=-1)
{
var mylookupId = (MyCombobox.SelectedItem as Lookup).id;// get your id and do further processing here.
}
}
I think this will be easy when using newtonsoft:
var dynamicObject = JObject.Parse(yourstring);
var list = new List<Lookup>();
//now you have a dynamic object containing an array.
//this should be doable with linq as well.
//note, the type is dynamic
foreach (dynamic thing in dynamicObject )
{
list.Add(new Lookup()
{
id = thing.fields.id,
SerialNumber = thing.fields.SerialNumber
});
}
disclaimer: not tested in any way ;-)

Manipulation multidimensional JSON array in C#

I need to manipulate the following JSON Array to compare the value for Company Id. Any suggestions how I can manipulate this.
{ "39513447": { "field": "39513447", "label": "CompanyId", "type": "number", "value": "5907" }, "39513458": { "field": "39513458", "label": "UserId", "type": "number", "value": "5904" }, "39380671": { "field": "39380671", "label": "Name", "type": "name", "value": "first = First\nlast = Name" }, "39380675": { "field": "39380675", "label": "Company Name", "type": "text", "value": "CompanyName" }, "39381333": { "field": "39381333", "label": "Planned Gross Salary Amount", "type": "number", "value": "11020" }, "39381266": { "field": "39381266", "label": "Per:", "type": "select", "value": "Annum" }, "39380485": { "field": "39380485", "label": "Planned Gross Dividend Amount", "type": "number", "value": "31980" }, "39381357": { "field": "39381357", "label": "Per:", "type": "select", "value": "Annum" }}
I have a class with these 3 properties:
public int id { get; set; }
public DateTime timestamp { get; set; }
public object data { get; set; }
Which I deserialize using:
T jsonObject = JsonConvert.DeserializeObject<T>(text);
Ideally want to deserialize into class with these 4 properties:
public string field { get; set; }
public string label { get; set; }
public string type { get; set; }
public string value { get; set; }
Create a class:
public class MyClass
{
public string field { get; set; }
public string label { get; set; }
public string type { get; set; }
public string value { get; set; }
}
And simple deserialize your json into a Dictionary:
var json = GetJsonString();
var dict = JsonConvert.DeserializeObject<Dictionary<int,MyClass>>(json);
Here's how to fetch data:
var curr = dict[39513447];
var field = curr.field;
var label = curr.label;
// etc.

Categories