This question already has answers here:
How can I use a reserved keyword as an identifier in my JSON model class?
(3 answers)
Closed 2 years ago.
I need to serialize a JSON string containing the following:
{
commandId;
id;
params:
{
userId;
password;
}``
}
The code I was given uses Qt and they declare a QJsonObject paramsObj and a QJsonObject cmdObj;
they fill the field values and finally perform a cmdObj.insert("params", QJsonValue(paramsObj));
params is a keyword for VS and C# so I can't declare a class with that name, but this is the way the device will understand my JSON strings.
I am fairly new to JSON and looked at the .Net class and the Newtonsoft library but can't find how to perform the insert of a JSON object inside another, assigning an arbitrary name to it.
Can anyone shed some light?
Thank you.
You just need to escape params with # like this:
public class MyObject
{
public Params #params { get; set; }
}
This produces:
{
"params": {}
}
Or use Params as property name and use CamelCasePropertyNamesContractResolver.
Related
This question already has answers here:
Detect if deserialized object is missing a field with the JsonConvert class in Json.NET
(5 answers)
Closed 5 years ago.
I have a simple class I want to deserialize a json string into :
public class ConnectClientResponse
{
public bool result { get; set; }
}
Call of the Deserialize method :
try
{
var response = JsonConvert.DeserializeObject<ConnectClientResponse>(jsonString);
}
catch (JsonSerializationException)
{
// Exception should be thrown
}
The issue is when the json string has the same form as the ConnectClientResponse class but the property name is not the same, no exception is thrown.
Is this a normal behaviour ? If so, how can I check if the properties names are the same ?
Exemple of invalid json, the property name doesn't match the ConnectClientResponse "result" property name :
{
"test" : true
}
Your actual problem is not that there's a "similar" property, but that your property isn't mandatory.
If you want certain properties to be mandatory, mark it with the JsonProperty attribute, e.g. [JsonProperty(Required = Required.Always)]. You can also use the value Required.AllowNull instead, if null values should be valid, as long as the property name is there.
You can use the MissingMemberHandling on JsonSerializerSettings to control this behaviour. https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_MissingMemberHandling.htm
This question already has answers here:
How to serialize/deserialize a custom collection with additional properties using Json.Net
(6 answers)
How do I get json.net to serialize members of a class deriving from List<T>?
(3 answers)
Closed 5 years ago.
We're switching our cache system over from a binary serializer (the one AppFabric uses) to a JSON serializer (For use with Redis) and I'm running into some incompatibilities with a few object types. The general idea is the same, we have a class that looks something like this:
[Serializable]
public class ActivityMeasurementIndexes : List<ActivityMeasurementIndex>
{
public int Id { get; set; }
public DateTime lastDbRead { get; set; }
public ActivityMeasurementIndexes()
{
lastDbRead = DateTime.Now;
}
}
The binary serializer will serialize and deserialize the object just fine. However, when I try to serialize the object with JSON.NET, I get:
var testObject = new ActivityMeasurementIndexes { Id = 5 };
Newtonsoft.Json.JsonConvert.SerializeObject(testObject);
"[]"
So, JSON.NET is basically serializing the base List<T> but the properties in the derived type are getting lost. I could probably refactor this class so it has a public List<ActivityMeasurementIndex> Items { get; set } instead, but we have quite a few of these classes and tons of code that would also have to be refactored.
Is there a good approach to handle this? I don't really care how the JSON looks as long as I can serialize and deserialize the base list as well as the properties on the class. I'm guessing I would need to write some sort of custom converter, or maybe there's something JSON.NET can do out of the box to help me out. Any hints for stuff to read up on would be great!
I Use JsonConvert to serialize an object and save it in a database. This is a sample of the serialized string that I saved in database:
[{"matId":"1","value":"44"},{"matId":"2","value":"55"},{"matId":"4","value":"77"}]
Now when I get this string from database which has a lot of backslashes like this:
"[{\"matId\":\"1\",\"value\":\"44\"},{\"matId\":\"2\",\"value\":\"55\"},{\"matId\":\"4\",\"value\":\"77\"}]"
And for this reason I can't Deserialize it.
.Replace("\\","") method doesn't create any affect on this. I don't know why.
You have to use JsonConvert.Deserialize method.
Your json string is wrapped within square brackets ([]), hence it is interpreted as array. Therefore, you need to deserialize it to type collection of one class, for example let's call it MyClass.
public class MyClass
{
public int matId { get; set; }
public int value { get; set; }
}
Here is Deserialize method.
var results=JsonConvert.DeserializeObject<List<MyClass>>(json);
Backslashes represent serialized object.
You need to deserialize your List object.
You can try using Generics:
public List<T> Deserialize<T>(string path)
{
return JsonConvert.DeserializeObject<List<T>>(path);
}
Be careful when looking at json strings as you are debugging. In Visual Studio it needs to format the value into a string. To do that it will add " so that it can process it when actually the value does not contain them. That is why the replace does not work.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# getting its own class name
For Visual Studio, I want to create a class template and use a string field that holds the name of a class itself. Is it possible?
For example:
public class MyClass
{
public string TAG = GetClassName(this);
}
When talking about non-static methods use Object.GetType Method which returns the exact runtime type of the instance (a reference to an instance of the Type Class):
this.GetType().Name
When talking about static methods, use MethodBase Class and its GetCurrentMethod Method :
Type t = MethodBase.GetCurrentMethod().DeclaringType;
//t.Name
However, see this post on SO for more info on this.
public string GetClassName(object item)
{
return typeof(item).Name;
}
Try following:
this.GetType().Name
Type.Name -> Gets the name of the current member.
This question already has answers here:
How to get the type of T from a member of a generic class or method
(17 answers)
Closed 9 years ago.
I'm working on a project where I have to reflect through data models to find out what type is in each property on a data models. I have the code working for all cases except for generic collections. I have to be able to what T is in IList.
I have the following data model
public class ArrryOfObjects
{
public NestModelNestedClass NestClass { get; set; }
public int IntObject { get; set; }
public IList<NestModelNestedClass> ListOfObjects { get; set; }
}
I've seen a couple of examples, like https://stackoverflow.com/a/1043778/136717 on how to do this, but they use the type.GetGenericTypeDefinition() to be get the type. But in my sample I cannot use this because 'type.IsGeneric.Parameter' is false.
I've review Type documentation and don't understand how to do this.
Try this:
var t = typeof(ArrryOfObjects)
.GetProperty("ListOfObjects")
.PropertyType
.GetGenericArguments()[0];
This is how it works:
From the type of ArrryOfObjects...
obtain the property called ListOfObjects...
get the type of that property...
which we know to be a generic type with at least one type parameter.
We get the first type parameter - in your example it should be typeof(NestModelNestedClass)
P.S. GetGenericTypeDefinition gets you typeof(IList<>), the generic type of which IList<NestModelNestedClass> is a generic instance.