JSON RPC Serializing Lists of Objects in c# - c#

So first some info about the project; here is a class I created :
public class SendOverview
{
public string id { get; set;}
public string method { get; set;}
public SendOV Params {get; set;}
}
public class SendOV
{
public string overviewID { get; set; }
public string overviewType { get; set; }
public string AORParams { get; set; }
public SentDatas arrOptions { get; set; }
}
public class SentDatas
{
public string columnInfo { get; set; }
public string orderInfo { get; set; }
}
A pretty simple class where I want to serialize the whole thing (So, the SendOverview class) by creating an object as done here :
SendOverview test1 = new SendOverview();
test1.id = "1";
test1.method = "getOverviewInfo";
SendOV testOV = new SendOV();
testOV.AORParams = null;
testOV.overviewID = tempDID;
testOV.overviewType = "Stock Items";
SentDatas col1 = new SentDatas();
col1.columnInfo = "1;100;1;1#";
col1.orderInfo = "1;0;0#";
Now once I try to add the col1 data to testOV's arrOptions I get a nullreference exception which blocks my work from any progress.. I have tried much, to no avail.
testOV.arrOptions[0] = col1;
is giving me the exception; Any help is highly appreciated..
(I know I have to create a List[] xx = new List[MAX] somewhere but I'm not able to implement it.)
COMPLIMENTARY QUESTION :
when sending the json string :
{\"id\":\"1\",\"method\":\"getOverviewInfo\",\"Params\":{\"overviewID\":\"0000004297\",\"overviewType\":\"Stock Items\",\"AORParams\":null,\"arrOptions\":{\"columnInfo\":\"1;100;1;1#\",\"orderInfo\":\"1;0;0#\"}}}"
All the named parameters should only have the value, not the named parameter; adjusted :
{\"id\":\"1\",\"method\":\"getOverviewInfo\",\"Params\":{"0000004297\","Stock Items",null,{\"columnInfo\":\"1;100;1;1#\",\"orderInfo\":\"1;0;0#\"}}}"
Which JSON property should I add to get this effect?
Thank you!

I am not entirely sure I understand what it is you are after, but take a look at the following and see if I am on the right track.
Update your class like so:
public class SendOV
{
public string overviewID { get; set; }
public string overviewType { get; set; }
public string AORParams { get; set; }
public List<SentDatas> arrOptions { get; set; }
}
And then update your creation code to this:
SendOverview test1 = new SendOverview();
test1.id = "1";
test1.method = "getOverviewInfo";
SendOV testOV = new SendOV();
testOV.AORParams = null;
testOV.overviewID = tempDID;
testOV.overviewType = "Stock Items";
List<SentDatas> sentDatasList = new List<SentDatas>();
SentDatas col1 = new SentDatas();
col1.columnInfo = "1;100;1;1#";
col1.orderInfo = "1;0;0#";
sentDatasList.Add(col1);
testOV.arrOptions = sentDatasList;

Related

Return null when passing data exists in c#

I have a problem that I am confused. I have a piece of code that executes a Post API command like this:
{
"chargeCriterias": null,
"containerType": "Dry",
"origin": {
"code": "ABC"
},
"destination": {
"code": "DYF"
},
"dateBegin": "2022-10-01T00:00:00",
"dateEnd": "2022-11-30T23:59:59",
"ratesFetcher": "XYZ",
}
I'm trying to write code to execute a command like this:
public class DataModel
{
public LocationModelBase origin { get; set; }
public LocationModelBase destination { get; set; }
public string dateBegin { get; set; }
public string dateEnd { get; set; }
public string chargeCriterias { get; set; }
public string containerType { get; set; }
public string ratesFetcher { get; set; }
}
public class LocationModelBase
{
public Int32 locationId { get; set; }
public string code { get; set; }
}
var addGetdata = new DataModel();
{
addGetdata.origin.code = "ABC";
addGetdata.destination.code = "DYF";
addGetdata.dateBegin = "2022-10-01T00:00:00";
addGetdata.dateEnd = "2022-11-30T23:59:59";
addGetdata.chargeCriterias = null;
addGetdata.containerType = "Dry";
addGetdata.ratesFetcher = "SSSS";
}
However I get the error: 'Object reference not set to an instance of an object.'.
I have checked the place value: addGetdata.origin and it says null. However I tried the ways but still didn't solve the problem. Where did I go wrong?
Looking forward to anyone's help or suggestions. Thank you
You are not creating an instance of the LocationModelBase on either the origin or destination so they default to null.
Either create them before you assign...
addGetdata.origin = new LocationModelBase();
addGetdata.origin.code = "ABC";
addGetdata.destination = new LocationModelBase();
addGetdata.destination.code = "DYF";
Or alternatively, create them as part of the construction of the class...
public LocationModelBase origin { get; set; } = new LocationModelBase();
public LocationModelBase destination { get; set; } = new LocationModelBase();
When initializing your DataModel class, you need to need initialize the other classes used for your model.
public LocationModelBase origin { get; set; }
public LocationModelBase destination { get; set; }
These properties have a type of another class and must be initialized before assigning values to that class' properties.
var addGetdata = new DataModel
{
origin = new LocationModelBase
{
code = "ABC"
},
destination = new LocationModelBase
{
code = "DYF"
}
...
}

how can I preserve my class after list clear

I have 2 classes
public class Product
{
public DateTime Date { get; set; }
public string Name { get; set; }
public int Amount { get; set; }
}
public class Campaign
{
public long CampaignId { get; set; }
public string CampaignName { get; set; }
public List<Product> Products { get; set; }
}
Code:
var campaign = new Campaign();
campaign.CampaignId = Item.CampaignId;
campaign.CampaignId = Item.CampaignId;
campaign.CampaignName = Item.CampaignName;
campaign.Products = productList;
campaignList.Add(campaign);
productList.Clear();
When I call productList.Clear(), my "campaign" deletes its campaign.Products.
How can I prevent that from happening?
campaign.Products = new List<Product>(productList);
because campaign.Products is the same reference of productList
they are both pointing to the same list , any action on one will be reflected in the other varialbe
you need to clone (make another copy of the list) by different ways as follwoing
campaign.Products = productList.GetClone();
or
campaign.Products = productList.ToList();
or
campaign.Products.AddRange(productList);
check the following url
https://www.techiedelight.com/clone-list-in-csharp/

Json conversion conundrum due to mixed type in List

All - I've stumbled into a scenario that's causing me quite a bit of grief. I have a json structure (produced by gateio api) which on the face of it, looks super simple to deserialize into an object. the jsonTickerString looks like the below:
{
"method":"ticker.update",
"params":[
"BTC_USDT",
{
"period":86400,
"open":"46721.06",
"close":"48130.43",
"high":"48758.59",
"low":"46330.3",
"last":"48130.43",
"change":"2.95",
"quoteVolume":"2246.8399550054",
"baseVolume":"106183751.468785134437"
}
],
"id":null
}
However, this is proving to be deceptively funky when trying to push it into an object model. I derived the object model below and thought we were all set to go:
public partial class GateIoTicker
{
[JsonProperty("method")]
public string Method { get; set; }
[JsonProperty("params")]
public List<ParamElement> Params { get; set; }
[JsonProperty("id")]
public object Id { get; set; }
}
public class ParamClass
{
[JsonProperty("period")]
public long Period { get; set; }
[JsonProperty("open")]
public string Open { get; set; }
[JsonProperty("close")]
public string Close { get; set; }
[JsonProperty("high")]
public string High { get; set; }
[JsonProperty("low")]
public string Low { get; set; }
[JsonProperty("last")]
public string Last { get; set; }
[JsonProperty("change")]
public string Change { get; set; }
[JsonProperty("quoteVolume")]
public string QuoteVolume { get; set; }
[JsonProperty("baseVolume")]
public string BaseVolume { get; set; }
}
public partial struct ParamElement
{
public string coinName;
public ParamClass quoteParams;
public static implicit operator ParamElement(ParamClass quoteparams)
{
return new ParamElement { quoteParams = quoteparams };
}
public static implicit operator ParamElement(string coinname)
{
return new ParamElement { coinName = coinname };
}
}
I then set about populating the object using the standard Json.Net approach:
var gateIoTicker = JsonConvert.DeserializeObject<GateIoTicker>(jsonTickerString);
However, although this correctly deserializes the string element in the "params" object, no amount of coersion will bring about a deserialization of the ParamClass object.
Am I missing something very obvious here?? I've spent an inordinate amount of time trying to figure this out and think it's now time to solicit some superior brain power.
Hope this scans as expected...
[Edit] - further to Serge's suggestion, i took his code and added it as a method on my GatIoTicker object. Would have preferred an option that desrializes using attributes, but this works perfectly. Refactored code looks like:
public partial class GateIoTicker
{
[JsonProperty("method")]
public string Method { get; set; }
[JsonProperty("params")]
public List<ParamElement> Params { get; set; }
[JsonProperty("id")]
public object Id { get; set; }
public GateIoTicker FromJson(string json)
{
var jsonObject = JObject.Parse(json);
var pars = jsonObject["params"] as JArray;
var paramElement = new ParamElement();
foreach (var jObject in pars)
{
if (jObject.GetType().Name.ToString() == "JValue") paramElement.ParamName = ((JValue)jObject).ToString();
else
{
paramElement.ParamBody = jObject.ToObject<ParamClass>();
}
}
GateIoTicker gateIoTicker = new GateIoTicker { Params = new List<ParamElement>() };
gateIoTicker.Id = (string)jsonObject["Id"];
gateIoTicker.Method = (string)jsonObject["method"];
gateIoTicker.Params.Add(paramElement);
return gateIoTicker;
}
}
public partial class ParamElement
{
public string ParamName { get; set; }
public ParamClass ParamBody {get; set;}
}
thanks again for the suggestions and nudges. seasons greetings
Try this, it was tested in Visual studio
var jsonObject = JObject.Parse(json);
var pars = jsonObject["params"] as JArray;
var paramElement = new ParamElement();
foreach (var jObject in pars)
{
if (jObject.GetType().Name.ToString() == "JValue") paramElement.ParamName = ((JValue)jObject).ToString();
else
{
paramElement.ParamBody=jObject.ToObject<ParamClass>();
}
}
GateIoTicker gateIoTicker = new GateIoTicker {Params= new List<ParamElement>()};
gateIoTicker.Id= (string) jsonObject["Id"];
gateIoTicker.Method= (string) jsonObject["method"];
gateIoTicker.Params.Add(paramElement);
ParamElement class
public partial class ParamElement
{
public string ParamName { get; set; }
public ParamClass ParamBody {get; set;}
}

Passing a generic list to a method

I have an application that will parse an excel file and add a column, then generate a new CSV file with the results. I am able to create a list of the items I want in the file, but I cannot figure out how to pass that list to the method that is generating the new file.
I have the following class:
public class LocationData
{
public string PostalCode { get; set; }
public string Partner { get; set; }
public string LocationID { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Market { get; set; }
}
and the following code to get the data into a list:
LocationData Locationdata = new LocationData()
{
PostalCode = location[0],
Partner = location[1],
LocationID = location[2],
Name = location[3],
Country = location[4],
Market = repository.GetMarketsForPostalCode(location[0])
}
I also have the method to create the csv and I need to pass in the list info, but I get the error:
foreach statement cannot operate on variables of type 'app.LocationData' because 'app.LocationData' does not contain a public definition for 'GetEnumerator'
I think you are misunderstanding what a list is in C#. I think you need the List data type. Try this:
List<string> Locationdata = new List<string>()
{
location[0],
location[1],
location[2],
location[3],
location[4],
repository.GetMarketsForPostalCode(location[0])
};
Your csv function will look like this
public void GenerateCSV(List<LocationData> data)
{
foreach (LocationData d in data)
{
//put line in csv as
string s = d.PostalCode + "," d.Partner + _"," + d.LocationID...... + Environment.NewLine;
}
}
Your class declaration will remain same
public class LocationData
{
public string PostalCode { get; set; }
public string Partner { get; set; }
public string LocationID { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Market { get; set; }
}
Now you need to add all the data in the list first
which you will do like this
List<LocationData> lst = new List<LocationData>();
LocationData ld = new LocationData();
ld.LocationID = "0";
ld.Market = "market";
lst.Add(ld);
........
GenerateCSV(lst);

Storing and retrieving from lists with custom structures in

I'm having some trouble storing and retrieving items into a list<> with a custom structure.
My structure looks like this:
public class list_rss_parameters
{
public string this_string { get; set; }
public string title_start { get; set; }
public string title_end { get; set; }
public string description_start { get; set; }
public string description_end { get; set; }
public string link_start { get; set; }
public string link_end { get; set; }
public string publish_date_start { get; set; }
public string publish_date_end { get; set; }
public string author_start { get; set; }
public string author_end { get; set; }
}
My stored procedure looks like this (and note that the variable names are the same as the custom Key names) Is this ok?
//this is the last part of a custom method that returns a list
List<list_rss_parameters> list_rss_items = new List<list_rss_parameters>();
list_rss_items.Add(new list_rss_parameters()
{
this_string = this_string,
title_start = title_start,
title_end = title_end,
description_start = description_start,
description_end = description_end,
link_start = link_start,
link_end = link_end,
publish_date_start = publish_date_start,
publish_date_end = publish_date_end,
author_start = author_start,
author_end = author_end
});
return list_rss_items;
If the above two setups are correct, how do I pull items out of the List once I return it?
List<list_rss_parameters> list_rss_parameters = new List<list_rss_parameters>();
list_rss_parameters = f_discover_rss_parameters(rss);
show(list_rss_parameters.Count.ToString());
show(list_rss_parameters[0].ToString()); //does not show this_string
show(list_rss_parameters[this_string'] //does not show this_string
show(list_rss_parameters[0][this_string'];//does not show this_string
What am I doing wrong?
You want the this_string property of the first item in your list it seems:
show(list_rss_parameters[0].this_string);
Or show all of them:
foreach(var item in list_rss_parameters)
{
Console.WriteLine(item.this_string);
}
As a side note your property names don't match the PascalCase naming convention for properties in .NET - so this_string really should be ThisString.

Categories