how to extract particular field from JSON using NewtonSoft.Json in C# - json

I am using Newtonsoft.Json in my C# application and want to know how to extract accountId from following JSON content which stored in string.
Any help is really appreciated.
{ "AccountListResponse": { "Accounts": { "Account": [ {"accountId":"0001","accountIdKey":"key1","accountMode":"ON"}, {"accountId":"00021","accountIdKey":"key21","accountMode":"ON"}, {"accountId":"00031","accountIdKey":"key31","accountMode":"ON"} ] } } }
i tried reading api, but still couldn't find out how to use. becaise of array, it got more complicated.

first here is your model
public class Account
{
public string accountId { get; set; }
public string accountIdKey { get; set; }
public string accountMode { get; set; }
}
public class AccountListResponse
{
public Accounts Accounts { get; set; }
}
public class Accounts
{
public List<Account> Account { get; set; }
}
public class AccountListResponseMain
{
public AccountListResponse AccountListResponse { get; set; }
}
then now you loop through
var regModel = new AccountListResponseMain();
regModel.AccountListResponse =data.AccountListResponse;
for (int a = 0; a < data.Accounts.Length; a++)
{
var inv = new Account();
inv.accountId = a.accountId;
}
N/B not perfect but you get the idea

Related

Need a help to deserialized nested json response

with the web api getting following response, want help to deserialize following json response in vb.net.
{
"data": {
"getReport": {
"report_date": "April 20, 2020",
"report_date_iso": "2020-04-20",
"links": {
"__typename": "Links",
"proportions_diagram": null
},
"results": {
"shape_and_cutting_style": "Emerald Cut",
"data": {
"shape": {
"shape_category": "F"
},
"girdle": null,
"inscription_graphics": []
}
},
"quota": {
"remaining": 4971
}
}
}
}
Thanks in advance
This worked perfect for me on .NET Core 3.1.
To test it:
In Visual Studio 2019, create a winform in .NET Core 3.1. Be sure it has the NuGet package for Newtonsoft.JSON.
Add a button called btnJsonConvTest, and a textbox called txtJSONinput.
Add a new class file to the project - name doesn't matter. Delete standard content from the file.
Select and copy your JSON. In Visual Studio, click Edit > Paste Special > Paste JSON as Classes. This will create the class structure you see below.
Add the bits of code from below. Note that I gave my class the name JSONTestObject.
Run your program, paste your JSON test string into the text box, and click the button.
Code:
using Newtonsoft.Json;
Button click event:
private void btnJsonConvTest_Click(object sender, EventArgs e)
{
JSONTestObject testobj = JsonConvert.DeserializeObject<JSONTestObject>(txtJSONinput.Text);
String res = JsonConvert.SerializeObject(testobj);
MessageBox.Show(res);
}
And the class that VS created for us:
public class JSONTestObject
{
public Data data { get; set; }
}
public class Data
{
public Getreport getReport { get; set; }
}
public class Getreport
{
public string report_date { get; set; }
public string report_date_iso { get; set; }
public Links links { get; set; }
public Results results { get; set; }
public Quota quota { get; set; }
}
public class Links
{
public string __typename { get; set; }
public object proportions_diagram { get; set; }
}
public class Results
{
public string shape_and_cutting_style { get; set; }
public Data1 data { get; set; }
}
public class Data1
{
public Shape shape { get; set; }
public object girdle { get; set; }
public object[] inscription_graphics { get; set; }
}
public class Shape
{
public string shape_category { get; set; }
}
public class Quota
{
public int remaining { get; set; }
}
When I test it, I get the same JSON string back out as went into it, thus proving that both the serialization and deserialization methods correctly move data in and out of the class properties.

The JSON string sequence differs from my JSON class,Please Suggest me how to Correct the Sequence

Getting below JSON Format where the sequence of the tags are wrong. how can i change the sequence of the JSON?
{
"HoldingRequest":{
"HoldingData":[
{
"dmat":"IN30051314972576",
"accountType":"CLNTBENE",
"action":null
},
{
"dmat":"IN30051314972576",
"accountType":"CLNTBENE",
"action":null
},
{
"dmat":"IN30051314972576",
"accountType":"CLNTBENE",
"action":null
}
],
"memberPan":"AAECS5096H",
"date":"20190914"
}
}
First three tags are placed at the end, but I want memberPan, date at the start
//Below is my class
public class JHoldingRequest
{
public JHoldingReqHeader HoldingRequest;
public class JHoldingReqHeader
{
public string memberPan { get; set; }
public string Date { get; set; }
public List<JHoldingReqDataList> HoldingData;
}
public class JHoldingReqDataList
{
public string dmat { get; set; }
public string accountType { get; set; }
public string action { get; set; }
}
}
///
Serializing
string json = string.Empty;
JNilHoldingRequest.JNilHoldingReqHeader objheader = new JNilHoldingRequest.JNilHoldingReqHeader();
json = new JavaScriptSerializer().Serialize(objheader);
Unfortunately, objects in Javascript (JavaScriptSerializer()) don't respect order.
If order is important, you need to work with arrays.

How to deserialize Nested json of wcf service to object

I've created a Web Service to receive data from Android json.
The json i receive is:
{
"assignmentId":"5476",
"newProductName":"ALGOBOX NET USB",
"Attributes": {
"Ammyy": "fvhbhgfc",
"Database": "h j j i i ",
"Plan": "555555555"
}
}
I want to deserialize the json and although i managed to deserialize the root elements, cannot deserialize the Nested:
"Attributes": {
"Ammyy": "fvhbhgfc",
"Database": "h j j i i ",
"Plan": "555555555"
}
The problem is that the attributes must be dynamic (Ammmy, Database, etc), so i cannot create a class with these strings. I want to deserialize the nested object to a Dictionary or KeyValuePair.
The classes that i've created are these:
public class RequestDataNewProduct
{
public string assignmentId { get; set; }
public string newProductName { get; set; }
public List<Atts> Attributes { get; set; }
}
public class Atts
{
public List<KeyValuePair<string, string>> Attributes { get; set; }
}
Any help?
the C# typed equivalent for your json should look like -
public class Attributes
{
public string Ammyy { get; set; }
public string Database { get; set; }
public string Plan { get; set; }
}
public class RequestDataNewProduct
{
public string assignmentId { get; set; }
public string newProductName { get; set; }
public Attributes Attributes { get; set; }
}
Then just deserialize it -
var t = JsonConvert.DeserializeObject<RequestDataNewProduct>(json); //success
Console.WriteLine(t.Attributes.Ammyy); //fvhbhgfc

RestSharp JSON List Deseralization

I launched this code:
var responseSection = client.Execute<List<SectionResponse>>(requestSection);
The response I should get:
[
{"SectionId":644852,"Name":"GDTC-MOBL-01-15W","Description":{"Text":"","Html":""},"Enrollments":[]},
{"SectionId":644853,"Name":"GDTC-MOBL-02-15W","Description":{"Text":"","Html":""},"Enrollments":[]}
]
The groups of my data classes:
public class SectionResponse
{
public List<SectionList> sectionList { get; set; }
}
public class SectionList
{
public int SectionId { get; set; }
public string Name { get; set; }
public Description_t Description { get; set; }
public List<Enrollments_t> Enrollments { get; set; }
}
public class Description_t
{
public string Text { get; set; }
public string Html { get; set; }
}
public class Enrollments_t
{
}
The problem is it attempts twice (two lists) but each request returns null data.
What should I do to get data?
Thanks in advance,
Phillip
You're saying you want a list of SectionResponses, which itself contains a list, so basically you're saying you want a list of lists, which doesn't match the response.
Try either this:
var responseSection = client.Execute<SectionResponse>(requestSection);
or this:
var responseSection = client.Execute<List<SectionList>>(requestSection);

Exporting class containing an ObservableCollection to csv in C#

I've found many solutions for exporting a class to CSV but my problem is this:
The class I'm trying to export has a property that is an observablecollection. eg:
public class ShipmentForExport
{
public string WaybillNumber { get; set; }
public DateTime WaybillDate { get; set; }
public string CustomerName { get; set; }
public string CustomerCode { get; set; }
public string CollectingBranchName { get; set; }
public string CollectingBranchCode { get; set; }
public string RecipientName { get; set; }
public string RecipientPhoneNumber { get; set; }
public string RecipientCellphoneNumber { get; set; }
public string RecipientCompany { get; set; }
public string DestinationAddress1 { get; set; }
public string DestinationAddress2 { get; set; }
public string DestinationCity { get; set; }
public string DestinationSuburb { get; set; }
public string DestinationProvince { get; set; }
public string DestinationCountry { get; set; }
public string DestinationPostalCode { get; set; }
***public ObservableCollection<InHouseParcel> Parcels { get; set; }***
}
When I try export a list of shipments to csv it works but obviously the parcels do not export the way I want them to.
I have tried using Filehelpers Library and csvHelper as well.
Any help is greatly appreciated!!
Josh's answer is outdated nowadays. You can use a typeconverter like:
CsvHelper.TypeConversion.TypeConverterFactory.AddConverter<ObservableCollection<string>>(new CsvHelper.TypeConversion.StringListConverter());
using (var txt = new StreamReader(filename))
using (var reader = new CsvHelper.CsvReader(txt))
{ .... }
namespace CsvHelper.TypeConversion
{
public sealed class StringListConverter : DefaultTypeConverter
{
public override object ConvertFromString(TypeConverterOptions options, string text)
{
var oc = new ObservableCollection<string>();
if (text.IndexOf('|') >= 0)
{
var list = text.Split('|').ToList<string>();// base.ConvertFromString(options, text);
oc = new ObservableCollection<string>(list);
}
return oc;
}
public override string ConvertToString(TypeConverterOptions options, object value)
{
var l = value as IEnumerable<string>;
if ( l == null || l.Count() == 0)
{
return "";
}
return string.Join("|", l);
}
public override bool CanConvertFrom(Type type)
{
return type == typeof(string);
}
}
}
Using CsvHelper (a library I maintain)...
When writing, you'll have to write manually because writing of collection properties isn't supported.
foreach( var record in records )
{
csv.WriteField( record.WaybillNumber );
...
foreach( var parcel in record.Parcels )
{
csv.WriteField( parcel );
}
}
Reading is a little easier because you can add it in the mapping.
Map( m => m.Parcels ).ConvertUsing( row =>
{
var oc = new ObservableCollection<InHouseParcel>();
var parcel = row.GetField<InHouseParcel>( 17 );
oc.Add( parcel );
} );
You'll need to convert the field values into InHouseParcel and loop through the remainder of the fields in the row. I'll leave that task to you.