Hi guys how do I get this to work? I searched in SO and this was the most promissing but it doesnt work either.
errormessage:
The deserialized type should be a normal .NET type (i.e. not a
primitive type like integer, not a collection type like an array or
List) or a dictionary type (i.e. Dictionary).
so how do i split the individual objects from my json?
List<class> a = JsonConvert.DeserializeObject<List<class>>(JSON_String)
the JSON string:
{
"SPALTEN": [{
"NUMMER": 1,
"NAME": "BREITE",
"TYP": "Double",
"LAENGE": 0,
"EINHEIT": "m",
"EDITIERBAR": true,
"OPTIONAL": true,
"LAYER": null,
"LAYER_SPALTE": null,
"D_SPAL_NAME": null,
"D_SPAL_MIN": 0,
"D_SPAL_MAX": null,
"D_SPAL_VAL": null
}, {
"NUMMER": 2,
"NAME": "KOMMENTAR",
"TYP": "String",
"LAENGE": 255,
"EINHEIT": null,
"EDITIERBAR": true,
"OPTIONAL": true,
"LAYER": null,
"LAYER_SPALTE": null,
"D_SPAL_NAME": null,
"D_SPAL_MIN": null,
"D_SPAL_MAX": null,
"D_SPAL_VAL": null
}]
}
here is my class:
public class CONFIG_CLASS
{
private int _NUMMER;
public int NUMMER
{
get { return _NUMMER; }
set { _NUMMER = value; }
}
private string _NAME;
public string NAME
{
get { return _NAME; }
set { _NAME = value; }
}
private string _TYP;
public string TYP
{
get { return _TYP; }
set { _TYP = value; }
}
private double _LAENGE;
public double LAENGE
{
get { return _LAENGE; }
set { _LAENGE = value; }
}
private string _EINHEIT;
public string EINHEIT
{
get { return _EINHEIT; }
set { _EINHEIT = value; }
}
private bool _EDITIERBAR;
public bool EDITIERBAR
{
get { return _EDITIERBAR; }
set { _EDITIERBAR = value; }
}
private bool _OPTIONAL;
public bool OPTIONAL
{
get { return _OPTIONAL; }
set { _OPTIONAL = value; }
}
private string _LAYER;
public string LAYER
{
get { return _LAYER; }
set { _LAYER = value; }
}
private int _LAYER_SPALTE;
public int LAYER_SPALTE
{
get { return _LAYER_SPALTE; }
set { _LAYER_SPALTE = value; }
}
private string _D_SPAL_NAME;
public string D_SPAL_NAME
{
get { return _D_SPAL_NAME; }
set { _D_SPAL_NAME = value; }
}
private int _D_SPAL_MIN;
public int D_SPAL_MIN
{
get { return _D_SPAL_MIN; }
set { _D_SPAL_MIN = value; }
}
private int _D_SPAL_MAX;
public int D_SPAL_MAX
{
get { return _D_SPAL_MAX; }
set { _D_SPAL_MAX = value; }
}
private string _D_SPAL_VAL;
public string D_SPAL_VAL
{
get { return _D_SPAL_VAL; }
set { _D_SPAL_VAL = value; }
}
}
(I would also like to encode it again later)
thank you!
You should specify the type of thing you want to deserialise, I don't think object will work.
List<MyClass> a = JsonConvert.DeserializeObject<List<MyClass>>("[{some json}]")
Sorry I cannot put comments yet
First,you have some type mismatch between your data and your convert class:
LAYER_SPALTE, D_SPAL_MIN and D_SPAL_MAX are null in your data.
put try putting your array inside another class
this code has to work for you:
public class MyClass
{
public SPALTEN[] SPALTEN { get; set; }
}
public class SPALTEN
{
public int NUMMER { get; set; }
public string NAME { get; set; }
public string TYP { get; set; }
public int LAENGE { get; set; }
public string EINHEIT { get; set; }
public bool EDITIERBAR { get; set; }
public bool OPTIONAL { get; set; }
public string LAYER { get; set; }
public int? LAYER_SPALTE { get; set; }
public string D_SPAL_NAME { get; set; }
public int? D_SPAL_MIN { get; set; }
public int? D_SPAL_MAX { get; set; }
public string D_SPAL_VAL { get; set; }
}
and then
MyClass a = JsonConvert.DeserializeObject<MyClass>(JSON_String)
To convert it on Internet, you can use the below URL for JSON to C#. I have been using from so long.
http://json2csharp.com/
Related
The propblem: There is no "Name" field in the object or csv file, yet CsVHelper keeps looking for "Name" in the header. So why is it tripping there and what are some fixes?
When trying to build objects from a csv file, the following error comes up:
CsvHelper.HeaderValidationException: Header with name 'Name' was not found. If you are expecting some headers to be missing and want to ignore this validation, set the configuration HeaderValidated to null. You can also change the functionality to do something else, like logging the issue.
at CsvHelper.Configuration.ConfigurationFunctions.HeaderValidated(Boolean isValid, String[] headerNames, Int32 headerNameIndex, ReadingContext context)
I have tried setting HeaderValidated to null, but got the same results.
The header of the csv:
Id|Title|Description|AssignedToUserId|SourceUserId|DateCreated|DateAssigned|DateCompleted|Notes
The parsing code:
private static IEnumerable<T> GetCSVData<T>(string fullFileName)
{
PrintMembers<T>();
using (var reader = new StreamReader(fullFileName))
{
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Configuration.HasHeaderRecord = true;
csv.Configuration.IncludePrivateMembers = false;
csv.Parser.Configuration.Delimiter = "|";
var records = csv.GetRecords<T>().ToList();
return records;
}
}
}
A quick function for listing the public properties and fields of the class (T) being passed in outputs the following:
Properties...
Id
AssignedToUserId
SourceUserId
Title
Description
AssignedTo
Source
DateCreated
DateAssigned
DateCompleted
RelatedTasks
Notes
Fields...
[None]
They all have getters and setters.
EDIT
The IntermediateTask is the generic being fed into GetCSVData(). It has a default constructor. IntermediateTask is internal, but is in the same assembly as GetCSVData().
Code for the class(es) in question:
internal class IntermediateTask : Task
{
private int _Id;
new public int Id
{
get { return _Id; }
set { _Id = value; }
}
private int _AssignedToUserId;
public int AssignedToUserId
{
get { return _AssignedToUserId; }
set
{
_AssignedToUserId = value;
base.AssignedTo = userManager.Get(_AssignedToUserId);
}
}
private int _SourceUserId;
public int SourceUserId
{
get { return _SourceUserId; }
set
{
this._SourceUserId = value;
base.Source = userManager.Get(_SourceUserId);
}
}
public IntermediateTask() : base("", "", new IntermediateUser(), new IntermediateUser())
{
}
}
public class Task
{
public Task(string title, string description, User assignedTo, User source, DateTime? dateCreated = null, int id = 0)
{
this.RelatedTasks = new List<Task>();
this.Title = title;
this.Description = description;
this.AssignedTo = assignedTo;
this.Source = source;
this.DateCreated = dateCreated ?? DateTime.Now;
this.Id = id;
}
private int _Id;
public int Id
{
get { return _Id; }
protected set { _Id = value; }
}
public string Title { get; set; }
public string Description { get; set; }
public User AssignedTo { get; set; }
public User Source { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateAssigned { get; set; }
public DateTime? DateCompleted { get; set; }
public IList<Task> RelatedTasks { get; set; }
public string Notes { get; set; }
override public string ToString()
{
return $"Id: {Id}; Title: {Title}";
}
}
In my case it complained about AssignedTo missing, but that is actually a property in the class that is not in the csv, so I had to add these two lines to make it work:
csv.Configuration.HeaderValidated = null;
csv.Configuration.MissingFieldFound = null;
I don't know why it would come up with 'Name' unless you have something different.
I have a project programmed in C# NET 3.5 in WPF which start very well in debug. However for example, in my TemplateColor.cs class I have this:
using System;
using System.Windows.Media;
namespace EWIN_THEME_MAKER.ThemeMaker
{
public class TemplateColor
{
private int _id;
private string _name;
private string _toneName;
public int ID
{
get
{
return this._id;
}
set
{
this._id = value;
}
}
public int AllVerticalPos
{
get;
set;
}
public int AllHorizontalPos
{
get;
set;
}
public int HuePageNum
{
get;
set;
}
public int HuePos
{
get;
set;
}
public int TonePaneNum
{
get;
set;
}
public int TonePos
{
get;
set;
}
public string Name
{
get
{
return this._name;
}
set
{
this._name = value;
string[] array = this._name.Split(new char[]
{
'_'
});
this._toneName = array[0];
if (array.Length > 1)
{
this.HuePageNum = int.Parse(array[1]);
}
}
}
public string ToneName
{
get
{
return this._toneName;
}
set
{
this._toneName = value;
}
}
public Color DarkColor
{
get;
set;
}
public Color MainColor
{
get;
set;
}
public Color LightColor
{
get;
set;
}
public Color ShadowColor
{
get;
set;
}
public byte ShadowA
{
get;
set;
}
public Color GrowColor
{
get;
set;
}
public Color TextShadowColor
{
get;
set;
}
public Color TextMainColor
{
get;
set;
}
public Color TextSelectColor
{
get;
set;
}
public double TextShadowPosition
{
get;
set;
}
public Brush DarkColorBrush
{
get
{
return new SolidColorBrush(this.DarkColor);
}
}
public Brush MainColorBrush
{
get
{
return new SolidColorBrush(this.MainColor);
}
}
public Brush LightColorBrush
{
get
{
return new SolidColorBrush(this.LightColor);
}
}
public Brush ShadowColorBrush
{
get
{
return new SolidColorBrush(this.ShadowColor);
}
}
public Brush GrowColorBrush
{
get
{
return new SolidColorBrush(this.GrowColor);
}
}
public Brush TextShadowColorBrush
{
get
{
return new SolidColorBrush(this.TextShadowColor);
}
}
public Brush TextMainColorBrush
{
get
{
return new SolidColorBrush(this.TextMainColor);
}
}
public Brush TextSelectColorBrush
{
get
{
return new SolidColorBrush(this.TextSelectColor);
}
}
public TemplateColor()
{
this.ID = -1;
this.AllVerticalPos = -1;
this.AllHorizontalPos = -1;
this.HuePageNum = -1;
this.HuePos = -1;
this.TonePaneNum = -1;
this.TonePos = -1;
this.Name = "---";
this.DarkColor = default(Color);
this.MainColor = default(Color);
this.LightColor = default(Color);
this.ShadowColor = default(Color);
this.ShadowA = 0;
this.GrowColor = default(Color);
this.TextShadowColor = default(Color);
this.TextMainColor = default(Color);
this.TextSelectColor = default(Color);
this.TextShadowPosition = 0.0;
}
}
}
In this code, there are multiple errors of this kind:
An exception of type 'System.StackOverflowException
For example I take this part of the code there:
public string Name
{
get
{
return this._name;
}
set
{
this._name = value;
string[] array = this._name.Split(new char[]
{
'_'
});
this._toneName = array[0];
if (array.Length > 1)
{
this.HuePageNum = int.Parse(array[1]);
}
}
}
So, in the next lines of this code there is an infinite call? I do not know how to correct this error.
string[] array = this._name.Split(new char[]
And...
this.HuePageNum = int.Parse(array[1]);
How do we predict and correct these errors?
My problem is now solved.
Solution: Increasing the size of the stack
Thanks to all!
I try to create a program that consumes plugins with COM-interface.
I implement IClassFactory interface to create instances of plugin. The CreateInstance-Method is implemented this way:
public int CreateInstance(IntPtr pUnkOuter, ref Guid riid, out IntPtr ppvObject)
{
MessageBox.Show("TestClassFactory CreateInstance");
ppvObject = IntPtr.Zero;
if (pUnkOuter != IntPtr.Zero)
{
// The pUnkOuter parameter was non-NULL and the object does
// not support aggregation.
Marshal.ThrowExceptionForHR(ComNative.CLASS_E_NOAGGREGATION);
}
if (riid == new Guid(ManagerGuids.ClassId)
|| riid == new Guid(ComNative.IID_IDispatch)
|| riid == new Guid(ComNative.IID_IUnknown))
{
MessageBox.Show("Pre GetComInterfaceForObject");
// Create the instance of the .NET object
// The container has to be passed as property and not by constructor injection.
// This is because COM (de-)registration needs a constructor without parameters.
ppvObject = Marshal.GetComInterfaceForObject(new NetPlugin(), typeof(INetPlugin));
MessageBox.Show("Post GetComInterfaceForObject");
}
else
{
// The object that ppvObject points to does not support the
// interface identified by riid.
Marshal.ThrowExceptionForHR(ComNative.E_NOINTERFACE);
}
return WinError.S_OK;
}
The call of Marshal.GetComInterfaceForObject(new NetPlugin(), typeof(INetPlugin)); returns invalid argument error (E_INVALIDARG).
The arguments of the method:
NetPlugin:
[ClassInterface(ClassInterfaceType.None)]
[Guid(ManagerGuids.ClassId)]
[ComVisible(true)]
public class NetPlugin : INetPlugin
{
public NetPlugin()
{
}
[ComVisible(true)]
[DispIdAttribute(0x1)]
public String LastParameters
{
get { return ""; }
set { }
}
[ComVisible(true)]
[DispIdAttribute(0x2)]
public String Vendor
{
get { return "Company"; }
set { }
}
[ComVisible(true)]
[DispIdAttribute(0x3)]
public String Description
{
get { return "Test plugin written in .NET"; }
set { }
}
[ComVisible(true)]
[DispIdAttribute(0x4)]
public String Version
{
get { return "1.0"; }
set { }
}
[ComVisible(true)]
[DispIdAttribute(0x5)]
public String Category
{
get { return "Void"; }
set { }
}
[ComVisible(true)]
[DispIdAttribute(0x6)]
public String MenuEntry
{
get { return "NetPlugin"; }
set { }
}
[ComVisible(true)]
[DispIdAttribute(0x7)]
public String MessageString
{
get { return "NetPlugin"; }
set { }
}
[ComVisible(true)]
[DispIdAttribute(0x8)]
public String TooltipText
{
get { return "Tooltip NetPlugin"; }
set { }
}
[ComVisible(true)]
[DispIdAttribute(0x9)]
public String FriendlyName
{
get { return "NetPlugin FFFFF Friendly"; }
set { }
}
[ComVisible(true)]
[DispIdAttribute(0xa)]
public String BitmapResourceSmall
{
get { return "BitmapResourceSmall.bmp"; }
set { }
}
[ComVisible(true)]
[DispIdAttribute(0xb)]
public String BitmapResourceLarge
{
get { return "BitmapResourceLarge.bmp"; }
set { }
}
[ComVisible(true)]
[DispIdAttribute(0xc)]
public String Key
{
get { return ""; } // must be empty
set { }
}
[ComVisible(true)]
[DispIdAttribute(0xd)]
public String Reserved
{
get { return "Void"; }
set { }
}
[ComVisible(true)]
[DispIdAttribute(0xe)]
public Int32 Run()
{
//-- Return scode
return 0;
}
}
INetPlugin:
[Guid(ManagerGuids.InterfaceId), ComVisible(true)]
interface INetPlugin
{
[DispId(0x1)]
String LastParameters { get; set; }
[DispId(0x2)]
String Vendor { get; set; }
[DispId(0x3)]
String Description {get; set; }
[DispId(0x4)]
String Version { get; set; }
[DispId(0x5)]
String Category { get; set; }
[DispId(0x6)]
String MenuEntry { get; set; }
[DispId(0x7)]
String MessageString { get; set; }
[DispId(0x8)]
String TooltipText { get; set; }
[DispId(0x9)]
String FriendlyName { get; set; }
[DispId(0xa)]
String BitmapResourceSmall { get; set; }
[DispId(0xb)]
String BitmapResourceLarge { get; set; }
[DispId(0xc)]
String Key { get; set; }
[DispId(0xd)]
String Reserved { get; set; }
[DispId(0xe)]
Int32 Run();
}
The NetPlugin is registred this way:
RegistrationServices rs = new RegistrationServices();
bool b = rs.RegisterAssembly(System.Reflection.Assembly.GetExecutingAssembly(), AssemblyRegistrationFlags.SetCodeBase);
if (!b)
return 998;
String exePath = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath;
Registry.SetValue(#"HKEY_CLASSES_ROOT\CLSID\{" + ManagerGuids.ClassId + #"}\LocalServer32", "", exePath);
The INetPlugin is registred this way:
[HKEY_CLASSES_ROOT\Interface\InterfaceGUID]
[HKEY_CLASSES_ROOT\Interface\InterfaceGUID\ProxyStubClsid32]
#="{00020420-0000-0000-C000-000000000046}"
[HKEY_CLASSES_ROOT\Interface\InterfaceGUID\TypeLib]
#="{228a33a4-193a-4d6e-93ee-6aba49be9488}"
"Version"="1.0"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Interface\InterfaceGUID]
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Interface\InterfaceGUID\ProxyStubClsid32]
#="{00020420-0000-0000-C000-000000000046}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Interface\InterfaceGUID\TypeLib]
#="{228a33a4-193a-4d6e-93ee-6aba49be9488}"
"Version"="1.0"
I'll be very thankful for any help!
I have this Json file:
{"id":88319,"dt":1345284000,"name":"Benghazi",
"coord":{"lat":32.12,"lon":20.07},
"main":{"temp":306.15,"pressure":1013,"humidity":44,"temp_min":306,"temp_max":306},
"wind":{"speed":1,"deg":-7},
"weather":[
{"id":520,"main":"rain","description":"light intensity shower rain","icon":"09d"},
{"id":500,"main":"rain","description":"light rain","icon":"10d"},
{"id":701,"main":"mist","description":"mist","icon":"50d"}
],
"clouds":{"all":90},
"rain":{"3h":3}}
I can read the "name": "Benghazi" normally but the "temp":306.15 I can not read because it is inside "main":{}
I'm using a simple way to read, here is my C# code:
public class SkyWeather
{
string path = #"http://api.openweathermap.org/data/2.5/weather?q=Uberaba,br&units=metric";
string name;
string temp;
public string Name { get { return name; } set { name = value; } }
public string Temp { get { return temp; } set { temp = value; } }
public string GetTemperature()
{
var json = "";
try
{
json = new WebClient().DownloadString(path);
}
catch (Exception e)
{
return e.ToString();
}
string text = (string)json;
SkyWeather w = JsonConvert.DeserializeObject<SkyWeather>(text);
return w.temp;
}
}
How can I read it?
Assuming that SkyWeather represents the properties in your "main" object, you'll need to create another object that represents the wrapping object:
public class RootObject
{
public int id { get; set; }
public int dt { get; set; }
public string name { get; set; }
public SkyWeather main { get; set; }
}
... and then:
RootObject w = JsonConvert.DeserializeObject<RootObject>(text);
return w.main.temp;
This is the working class:
namespace Lite
{
public class Spec
{
public int ID { get; set; }
public string Name { get; set; }
public string FriendlyName { get; set; }
public int CategoryID { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string UOM { get; set; }
public int Pagination { get; set; }
public int ColoursFront { get; set; }
public int ColoursBack { get; set; }
public string Material { get; set; }
public int GSM { get; set; }
public string GSMUOM { get; set; }
public bool Seal { get; set; }
public Spec(int ID)
{
using (CrystalCommon.MainContext db = new CrystalCommon.MainContext())
{
var q = (from c in db.tblSpecifications where c.id == ID select c).SingleOrDefault();
if (q != null)
loadByRec(q);
}
}
public Spec(CrystalCommon.tblSpecification Rec)
{
loadByRec(Rec);
}
public void loadByRec(CrystalCommon.tblSpecification Rec)
{
this.ID = Rec.id;
this.Name = Rec.Title;
this.Width = Convert.ToInt32(Rec.FinishedSizeW.Value);
this.Height = Convert.ToInt32(Rec.FinishedSizeL.Value);
this.UOM = Rec.FlatSizeUOM;
this.Pagination = Rec.TxtPagination.Value;
this.ColoursFront = Convert.ToInt32(Rec.TxtColsF.Value);
this.ColoursBack = Convert.ToInt32(Rec.TxtColsB.Value);
this.Material = Rec.TxtMaterial;
this.GSM = Rec.TxtGSM.Value;
this.GSMUOM = Rec.txtGsmUnit;
this.Seal = Rec.TxtSeal.Value == 1;
}
public string displayDimensions()
{
return Width + " x " + Height + " " + UOM;
}
}
}
Then I try and modify the Name getter and setter:
namespace Lite
{
public class Spec
{
public int ID { get; set; }
// User friendly name if available otherwise fall back on spec name
public string Name { get {
if (null != FriendlyName)
return FriendlyName;
else
return Name;
}
set
{
Name = value;
}
}
public string FriendlyName { get; set; }
public int CategoryID { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string UOM { get; set; }
public int Pagination { get; set; }
public int ColoursFront { get; set; }
public int ColoursBack { get; set; }
public string Material { get; set; }
public int GSM { get; set; }
public string GSMUOM { get; set; }
public bool Seal { get; set; }
public Spec(int ID)
{
using (CrystalCommon.MainContext db = new CrystalCommon.MainContext())
{
var q = (from c in db.tblSpecifications where c.id == ID select c).SingleOrDefault();
if (q != null)
loadByRec(q);
}
}
public Spec(CrystalCommon.tblSpecification Rec)
{
loadByRec(Rec);
}
public void loadByRec(CrystalCommon.tblSpecification Rec)
{
this.ID = Rec.id;
this.Name = Rec.Title;
this.Width = Convert.ToInt32(Rec.FinishedSizeW.Value);
this.Height = Convert.ToInt32(Rec.FinishedSizeL.Value);
this.UOM = Rec.FlatSizeUOM;
this.Pagination = Rec.TxtPagination.Value;
this.ColoursFront = Convert.ToInt32(Rec.TxtColsF.Value);
this.ColoursBack = Convert.ToInt32(Rec.TxtColsB.Value);
this.Material = Rec.TxtMaterial;
this.GSM = Rec.TxtGSM.Value;
this.GSMUOM = Rec.txtGsmUnit;
this.Seal = Rec.TxtSeal.Value == 1;
}
public string displayDimensions()
{
return Width + " x " + Height + " " + UOM;
}
}
}
On my computer this compiles fine, but the server seems to crash when it runs. (First version works fine). My colleague compiled it on his machine and it threw a "Stack overflow error" apparently, but he's not around for me to get specifics on that right now.
Am I applying the getter correctly here?
This is an endless loop:
public string Name { get {
...
set
{
Name = value;
}
}
The setter will call itself repeatedly until you get the Stack overflow exception.
usually you have a backing variable, so it ends up like this
private string name;
public string Name {
get {
if (null != FriendlyName)
return FriendlyName;
else
return name;
}
set {
name = value;
}
}
Your set is referencing the property itself, and your get is referencing the property itself, both of these will cause a potentially endless loop leading to a StackOverflowException (no more stack space to push the current call into). You need to use a backing field:
private string _name;
public string Name
{
get
{
if (null != FriendlyName)
return FriendlyName;
else
return _name;
}
set
{
_name = value;
}
}
It looks as though you tried to turn an auto-property into a manual one. Auto-properties (public string Name { get; set; }) work because the compiler will create the backing field itself.
As a learning exercise, if you step through with the debugger and step into return Name or Name = value you will see first hand the code going back into the property you are already in.
This is much better.
string _name = "";
public string Name
{
get { return FriendlyName ?? _name; }
set { _name = value; }
}
One of your properties gets and sets itself, see:
public string Name
{
get {
if (null != FriendlyName)
return FriendlyName;
else
return Name; //<-- StackOverflow
}
set
{
Name = value; //<-- StackOverflow
}
}
You have a getter for Name, that calls the property Name, which will call the getter for Name, etc. You need a private field to back the property, and you need to access that backing field in your getter instead.
public string Name { get {
if (null != FriendlyName)
return FriendlyName;
else
return Name;
}
set
{
Name = value;
}
}
Name in the get/set refers to the property. You will need to define a backing field and use that.
If FriendlyName is null then the Name getter attempts to get the value from the Name getter - i.e. it loops. This is what causes the stack overflow.
No you should use a backing field. The error is in the else
public string Name { get {
if (null != FriendlyName)
return FriendlyName;
else
return Name;//error, you're calling the property getter again.
}