Why does Newtonsoft.Json not serialise this property? [duplicate] - c#

This question already has answers here:
How do I get json.net to serialize members of a class deriving from List<T>?
(3 answers)
Closed 5 years ago.
Consider the following program: (.NET Fiddle Link)
public class Program
{
public static void Main()
{
var carsa = new ListOfCarsA();
carsa.Cars.Add("Toyota");
carsa.Cars.Add("Lexus");
Console.WriteLine(JsonConvert.SerializeObject(carsa, Formatting.Indented));
var carsb = new ListOfCarsB();
carsb.Add("Nissan");
carsb.Add("Infiniti");
Console.WriteLine(JsonConvert.SerializeObject(carsb, Formatting.Indented));
}
}
public class ListOfCarsA
{
public string CollectionName { get { return "CarsA"; } }
public List<string> Cars { get; set; }
public ListOfCarsA()
{
Cars = new List<string>();
}
}
public class ListOfCarsB : List<string>
{
public string CollectionName { get { return "CarsB"; } }
}
This then outputs the following:
{
"CollectionName": "CarsA",
"Cars": [
"Toyota",
"Lexus"
]
}
And
[
"Nissan",
"Infiniti"
]
Why does the property CollectionName not get serialised and output CarsB, but the same property on the ListOfCarsA results in CarsA being serialised?
What is the solution to this problem - How could I have a class similar to ListOfCarsB but still have any extra members serialised? I have tried using the attributes [JsonProperty("CollectionName"] and [JsonRequired] but these seem to do nothing.

This is because your second example IS a list, whilst the first example only contains one. Json.Net knows how to create json from lists and so is ignoring the rest of your custom code. Not much you can do about this except write a custom formatter

Related

JSON.NET deserialize JSON then format string [duplicate]

This question already has answers here:
running a transformation on a Json DeserializeObject for a property
(2 answers)
Closed 3 years ago.
I have the following JSON:
{
"lastOcurrences":[
{
"myString":"16726354"
},
{
"myString":"66728744"
},
{
"myString":"91135422"
}
]
}
and I have a class to deserialize it on:
public class JsonObject
{
public List<LastOcurrence> LastOcurrences { get; set; }
}
public class LastOcurrence
{
public string MyString { get; set; }
}
Upon deserializing it with JsonConvert.DeserializeObject<T>(json), I'd like to be able to format the string myString, to store 167-263-54, instead of 16726354.
What solution would please my soul: Using attributes on the properties, something of the likes of JsonConverter, but...
What i'd like to avoid doing: I would not like to use reflection to iterate through every property, only to then read the attribute and apply the formatting. Is there any way of doing this 'automatically' with JsonConvert?
One possible solution is to use custom getters and setters for this and when it is deserialized you keep the raw data stored. This will do JIT formatting. Depending on the usage of this data this could be much quicker however if there are a lot of repeated reads of the same data then this may be a bit slower.
public class LastOcurrence
{
private string _myString;
public string MyString
{
get { return Regex.Replace(_myString, #"^(.{ 3})(.{ 3})(.{ 2})$", "$1-$2-$3"); }
set { _myString = value; }
}
}

How to deserialize JSON object using constructor into itself in C#? [duplicate]

This question already has answers here:
Overlay data from JSON string to existing object instance
(4 answers)
Closed 4 years ago.
I want to create a new object, and during object creation make an RPC call to get properties for it, and then return the object populated with the properties. See this example:
using Newtonsoft.Json;
class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(int Id)
{
// here would be an RPC call to get the FirstName,LastName. result is JSON
string result = "{\"Id\": 1, \"FirstName\": \"Bob\", \"LastName\": \"Jones\"}";
this = JsonConvert.DeserializeObject<Person>(result);
}
}
class Program
{
static void Main(string[] args)
{
var p = new Person(1);
// p.FirstName should be Bob
}
}
I don't know how to do this in the constructor without getting a StackOverflow Exception.
One option to consider is to use a static method inside Person:
public static Person GetPerson(int Id)
{
// here would be an RPC call to get the FirstName,LastName. result is JSON
string result = "{\"Id\": 1, \"FirstName\": \"Bob\", \"LastName\": \"Jones\"}";
return JsonConvert.DeserializeObject<Person>(result);
}
This avoids the recursive nature of your original code.
Another option is to change the class to a struct. structs allow you to assign to this (unlike classes). And they have a default constructor (separate to your one taking a parameter) so that there is no recursive behaviour.

C# JsonConvert.DeserializeObject to list / add item to array

I'm currently trying to add a item to a array. But I think a list would be way easier since I could use
list.Add("whatever");
Is there a way to receive the following as a list?
dynamic reps = JsonConvert.DeserializeObject("rep.json");
Example json:
{"reps": {
{
"username": "usera",
"reps": 10,
"latestrep": "userx"
},
"userb": {
"username": "userb",
"reps": 10,
"latestrep": "userx"
},
"userc": {
"username": "userc",
"reps": 10,
"latestrep": "userx"
}
}}
I appreciate any kind of help
Providing you have a class defining the list item:
public class UserReps
{
public string Username { get; set; }
public int Reps { get; set; }
public string LatestRep { get; set; }
}
You can achieve what you want with LINQ:
IDictionary<string, IDictionary<string, UserReps>> parsed = JsonConvert.DeserializeObject<IDictionary<string, IDictionary<string, UserReps>>>(json);
List<UserReps> userReps = parsed["reps"].Select(ur => ur.Value).ToList();
I think you are looking for something like this:
`
public static dynamic FromJsonToDynamic(this object value)
{
dynamic result = value.ToString().FromJsonToDynamic();
return result;
}
`
That is an extension method that I use for generic objects. If you are looking at something to convert it to a particular object you could create an extension method like this:
public static T FromJson<T>(this object value) where T : class
{
T result = value.ToString().FromJson<T>();
return result;
}
With your data as it is at the moment, no. Your input data doesnt appear to be a collection or something that could logically be 'listified'.

JSON C# .NET Compile Class Name [duplicate]

This question already has answers here:
Json.NET serialize object with root name
(10 answers)
Closed 8 years ago.
I am working on a C# project however I am in need of some advice.
I am presently posting to my site:
{Tags : 'App', Limit : '10' }
And it can cast this to the following class
[Serializable]
public class MiloFilter
{
public string Tags { get; set; }
public string Limit { get; set; }
}
However what I am wanting to accomplish is that I would like to post my JSON like this:
{ MiloFilter : {Tags : 'SomeTag', Limit : '1' }}
However when I try and parse it using the following method it fails.
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var miloFilter = js.Deserialize<MiloFilter>(bodyText);
How can I acomplish this?
You can easily create your own serializer
var car = new Car() { Name = "Ford", Owner = "John Smith" };
string json = Serialize(car);
string Serialize<T>(T o)
{
var attr = o.GetType().GetCustomAttribute(typeof(JsonObjectAttribute)) as JsonObjectAttribute;
var jv = JValue.FromObject(o);
return new JObject(new JProperty(attr.Title, jv)).ToString();
}
source

Deserialization of get only properties in C# using json.net / webapi [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Using Json.net - partial custom serialization of a c# object
I have a class that I successfully get to serialize in json.net when using asp.net MVC 4 WebAPI. The class has a property that is a list of strings.
public class FruitBasket {
[DataMember]
public List<string> FruitList { get; set; }
public int FruitCount {
get {
return FruitList.Count();
}
}
}
In my Get method the serialization happens ok and I get an empty array i.e. [] for the FruitList property in my JSON. If I use the same json in a PUT request's body I get an error in the FruitCount property during deserialization because FruitList is null.
I want the FruitList property (basically my get only properties) to serialize but not deserialize. Is it possible with a setting or other wise with json.net?
I realize this does not answer your question, but addresses the error being generated so might make worrying about custom serialization irrelevant
use a private variable for FruitList, return it in the get and in set, if value is null then set the private variable equal to a new list.
public class FruitBasket
{
private List<string> _fruitList;
[DataMember]
public List<string> FruitList
{
get
{
return _fruitList;
}
set
{
if (value == null)
{
_fruitList = new List<string>();
}
else
{
_fruitList = value;
}
}
}
public int FruitCount
{
get
{
return FruitList.Count();
}
}
}

Categories