Deserialize complex json in C# - json

I have this json and need to parse the nested details. using Newtonsoft.Json for Deserializing but cant really parse this complex json.
{
"name": "John",
"email": "john#gmail.com",
"data": [
{
"company_name": "instagram",
"company_email": "abc#email.com",
"org": {
"org_name": "john-insta",
"org_dob": "1/1/1990",
}
},
{
"company_name": "google",
"company_email": "abc1#email.com",
"org": {
"org_name": "john-google",
"org_dob": "1/1/1990",
}
},
]
The number of entries in "data" may actually be varying dynamically, how do I parse the entries for company_name, company_email, org_name,org_dob.

What is the problem you are having? This seems fairly simple JSON array. Setup your classes like this.
public class MyClass
{
public string name { get; set; }
public string email { get; set; }
public List<DataClass> data { get; set; }
}
public class DataClass
{
public string company_name { get; set; }
public string company_email { get; set; }
public Org org { get; set; }
//Any other and all possible properties...
}
public class Org
{
public string org_name { get; set; }
public string org_dob { get; set; }
}
Then it can be parsed using Newtonsoft or similar using.
var test = JsonConvert.DeserializeObject<MyClass>(json);
This method also has an overload where you can pass settings to ignore nulls.
var test = JsonConvert.DeserializeObject<MyClass>(json,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

Related

Error deserializing json with nested arrays

I'm trying to deserialize a json object that includes nested arrays and I get the following error when I try it in Postman:
{
"errors": {
"accounts": [
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Orders.Dtos.Accounts' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.\r\nTo 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.\r\nPath 'accounts', line 7, position 17."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-92466567188264cbdc71e6f6d7479688-fe08150cd947ddf1-00"
}
Simplified json to deserialize:
{
"plannedShippingDateAndTime": "2023-02-07T07:06:00 GMT+01:00",
"pickup": {
"isRequested": false
},
"productCode": "N",
"accounts": [
{
"typeCode": "shipper",
"number": "999999999"
}
]
}
Classes:
public class ShipmentData
{
public string PlannedShippingDateAndTime { get; set; }
public Pickup Pickup { get; set; }
public string ProductCode { get; set; } = "N";
public Accounts Accounts { get; set; }
}
public class Pickup
{
public bool isRequested { get; set; }
}
public class Accounts
{
public ArrayAccounts[] ArrayAccounts { get; set; }
}
public class ArrayAccounts
{
public string TypeCode { get; set; }
public string Number { get; set; }
}
Api Controller:
[HttpPost("CreateShipment/{OrderId}")]
public async Task<ActionResult> CreateShipment(string OrderId, ShipMentData shipmentData)
{
...
}
public class ShipmentData
{
public string PlannedShippingDateAndTime { get; set; }
public Pickup Pickup { get; set; }
public string ProductCode { get; set; }
public Account[] Accounts { get; set; }
}
public class Pickup
{
public bool IsRequested { get; set; }
}
public class Account
{
public string TypeCode { get; set; }
public string Number { get; set; }
}
Also Customize JSON binding:
options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;

JSON DeserializeObject Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

When I deserialize JSON to my class using Newtonsoft JSON.net, I get this error. What could be the cause of it ? Certainly I am missing something obvious..
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
Here is my JSON:
[
{
"AgreementUID": "a8ea9f59-82f3-4799-b684-06a2cd95d9a1",
"ProjectUID": "851D12CE-7DC3-E511-9C58-F0DEF17C096F",
"year": "2016",
"data": [
{
"month": 1,
"B": "4",
"P": "1",
"F": "1"
},
{
"month": 2,
"B": "",
"P": "",
"F": ""
}
]
}
]
Here is my Class:
public class AgreementBreakdownObject
{
public string AgreementUID { get; set; }
public string ProjectUID { get; set; }
public string year { get; set; }
public List<AgreementBreakdownDataObject> data { get; set; }
}
public class AgreementBreakdownDataObject
{
public int month { get; set; }
public string B { get; set; }
public string P { get; set; }
public string F { get; set; }
}
I do deserialize like this:
string jsonData = hData.Value;
var data = JsonConvert.DeserializeObject<List<AgreementBreakdownObject>> (jsonData);
Please suggest what is my mistake here. thank you
You'll need to escape your quotes if the json is within a C# string. Example below:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace ConsoleApp3
{
public class AgreementBreakdownObject
{
public string AgreementUID { get; set; }
public string ProjectUID { get; set; }
public string year { get; set; }
public List<AgreementBreakdownDataObject> data { get; set; }
}
public class AgreementBreakdownDataObject
{
public int month { get; set; }
public string B { get; set; }
public string P { get; set; }
public string F { get; set; }
}
class Program
{
static void Main(string[] args)
{
var data = JsonConvert.DeserializeObject<List<AgreementBreakdownObject>>(#"[
{
""AgreementUID"": ""a8ea9f59-82f3-4799-b684-06a2cd95d9a1"",
""ProjectUID"": ""851D12CE-7DC3-E511-9C58-F0DEF17C096F"",
""year"": ""2016"",
""data"": [
{
""month"": 1,
""B"": ""4"",
""P"": ""1"",
""F"": ""1""
},
{
""month"": 2,
""B"": """",
""P"": """",
""F"": """"
}
]
}
]");
Console.WriteLine(JsonConvert.SerializeObject(data, Formatting.Indented));
Console.ReadKey();
}
}
}
Relevant excerpt from MSDN:
Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. Because verbatim strings preserve new line characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string.

How to Deserialize Complex JSON file in SSIS into few columns

I have a JSON file that is pretty complex. Here is a snippet of my file:
JSON
"SKU": "12345",
"Status": {
"Health": "OK"
},
"Type": "ComputerSystem",
"Name": "Cartridge 1",
"Power": "Off",
"AssetTag": "12345",
"HostCorrelation": {
"IPAddress": [],
"HostMACAddress": [
"00:00:00:00:00:00",
"11:11:11:11:11:11"
]
},
"SerialNumber": "12345",
"Boot": {
"BootSourceOverrideSupported": [
"None",
"PXE",
"HDD",
"iSCSI",
"M.2",
"None"
],
"BootSourceOverrideTarget": "PXE",
"BootSourceOverrideEnabled": "Continuous"
}
Without showing all the classes here is the RootObject VS generates as code:
Paste JSON as Class
public class Rootobject
{
public string SKU { get; set; }
public Status Status { get; set; }
public string Type { get; set; }
public string Name { get; set; }
public string Power { get; set; }
public string AssetTag { get; set; }
public Hostcorrelation HostCorrelation { get; set; }
public string SerialNumber { get; set; }
public Boot Boot { get; set; }
public Links links { get; set; }
public string UUID { get; set; }
public Bios Bios { get; set; }
public Oem Oem { get; set; }
public Memory Memory { get; set; }
public Availableaction[] AvailableActions { get; set; }
public string SystemType { get; set; }
public Processors Processors { get; set; }
public string Model { get; set; }
public string Manufacturer { get; set; }
}
I want to loop through multiple JSON files with this structure, and put them into a few columns such as (Section, Component, Property, and Value).
However, I have been having a hard time figuring this out. It would be simple to put each part into its own unique column.
The end result of my JSON example above may look like:
Goal SQL Output
The format doesn't have to be exact, but something along those lines. If there is a better way of doing this I am all ears.
I can tell you didn't post all of your classes because the RootObject has object references, but this is how you could start your code. This won;t get your data into the format you asked for, but it is how the serializer works.
string json = [Somehow get your json in to a string]
JavaScriptSerializer js = new JavaScriptSerializer();
var jRow = js.Deserialize<Rootobject>(json);
// now you have your entire JSON in one object.
//for the data you presented you will need a few outputs:
// let's start with the outermost:
Output0Buffer.AddRow();
Output0Buffer.SKU = jRow.SKU;
Output0Buffer.Health = jRow.Status.Health; //There is only one option here
Output0Buffer.Type = jRow.Type ;
Output0Buffer.Name = jRow.Name;
Output0Buffer.Power = jRow.Power ;
Output0Buffer.AssetTag = jRow.AssetTag ;
Output0Buffer.SerialNumber = jRow.SerialNumber ;
Output0Buffer.BootSourceOverrideTarget= jRow.Boot.BootSourceOverrideTarget ;
Output0Buffer.BootSourceOverrideEnabled= jRow.Boot.BootSourceOverrideEnabled;
//this is a new output of boot details linked by SKU
foreach(var dtl in jRow.Boot.BootSourceOverrideSupported)
{
OutputBootStuffBuffer.AddRow();
OutputBootStuffBuffer.SKU = JRow.SKU; //Making assumption that SKU is the key back
OutputBootStuffBuffer.BootSourceOverrideSupported = dtl.BootSourceOverrideSupported;
}

JSON. A reference deserializes to null

I am using Newtonsoft.json. I can't understand result of a deserialization. Bulletin.PageList is being filled ok. But Page of Question which is referencing to element of PageList is always null. In the JsonSerializerSettings I specified PreserveReferencesHandling.All but it didn't help. Could you help to resolve the problem of null of Page? Thank you
JSON structure:
"Bulletins": [
{
"$id": "46b5efa80fe644d7bd525e2c30f5df8a",
"$type": "Bulletin",
"JSONNETTYPE": "Bulletin",
"PagesList": [
{
"id": "4ed13d727cd144d1acf1e0c9bc273245",
"JSONNETTYPE": "PageView",
"Number": 1,
"Id": "1a2b8ed4249948e194b396c46a5d1eeb",
"UiId": "4ed13d727cd144d1acf1e0c9bc273245"
}
],
"AgendaQuestions": [
{
"$id": "eceb6fe6c74a40d59f0673b76bd6dbb3",
"$type": "QSimple",
"Page": {
"$ref": "46b5efa80fe644d7bd525e2c30f5df8a#PagesList.0"
}
}
]
}]
C# structure:
public class Bulletin
{
public Bulletin()
{
}
public string Dbid { get; set; }
public List<PageView> PagesList;
public List<Question> AgendaQuestions;
}
public abstract class Question
{
protected Question(int number, string customNumberLabel = null)
{
Number = number;
CustomNumberLabel = customNumberLabel;
}
public int Number { get; set; }
public string CustomNumberLabel { get; set; }
public PageView Page { get; set; }
}
public class PageView
{
public int Number { get; set; }
public string Id { get; set; }
public int BulletinNumber { get; set; }
public PageView()
{
}
}
var settings = new JsonSerializerSettings
{ PreserveReferencesHandling = PreserveReferencesHandling.All
}
I was using dojox.json.ref library. If I set __id for Page, references to elements of PagesList will become direct, not complex (like 46b5efa80fe644d7bd525e2c30f5df8a#PagesList.0), and Page is filled.

How to display JSON data in Xamarin.forms list view?

I am new to xamarin.forms, and i want to build an cross platform app that will display JSON data in the list view. This is my JSON data.
{
"fish_product": [
{
"fish_id": "1",
"fish_img": "",
"fish_name": "Indian Mackerel",
"fish_category": "Marine Fish",
"size": "Medium",
"price": "100"
},
{
"fish_id": "2",
"fish_img": "",
"fish_name": "Manthal Repti",
"fish_category": "Marine Fish",
"size": "Small",
"price": "200"
},
{
"fish_id": "4",
"fish_img": "",
"fish_name": "Baby Sole Fish",
"fish_category": "Marine Fish",
"size": "Small",
"price": "600"
}
]
}
I want to display "fish_name" in list view. please suggest any solution or any article or tutorial for this. thank you in advance.
I think you have to deserialize this JSON to an object like
public class FishProduct
{
public string fish_id { get; set; }
public string fish_img { get; set; }
public string fish_name { get; set; }
public string fish_category { get; set; }
public string size { get; set; }
public string price { get; set; }
}
public class RootObject
{
public ObservableCollection<FishProduct> fish_product { get; set; }
}
Then you have to use a ListView where you set your listview.ItemsSource = myList.fish_product
Then you have to create a DataTemplate using ViewCell
In this ViewCell you can have a Label when you SetBinding the fish_name field. In code something like
Label label = new Label();
label.SetBinding(Label.TextProperty, "fish_name");
I think you can take a look to ListView Documents
I think this may help you
Your MODEL
public class FishProduct
{
public string fish_id { get; set; }
public string fish_img { get; set; }
public string fish_name { get; set; }
public string fish_category { get; set; }
public string size { get; set; }
public string price { get; set; }
}
public class RootObject
{
public List<FishProduct> fish_product { get; set; }
}
Webservice call and JSON Deserialisation
public async Task GetData()
{
try
{
HttpClient client = new HttpClient();
var result = await client.GetAsync("http://yourJSON_Url");
result.EnsureSuccessStatusCode();
string json = await result.Content.ReadAsStringAsync();
List<FishProduct> res= JsonConvert.DeserializeObject<List<FishProduct>>(json);
}
catch (Exception ex)
{
throw;
}
}