This question already has an answer here:
How to exclude properties from JsonConvert.PopulateObject that don't exist in some base type or interface?
(1 answer)
Closed 3 years ago.
I am trying to save the following data in the Json form. I am using the Newtonsoft.Json library for that. Sometimes I need to serialize only the RecipeShort properties of the Recipe object.
[JsonObject(MemberSerialization.OptIn)]
public class RecipeShort
{
[JsonProperty]
public string Id { get; set; }
[JsonProperty]
public string Title { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class Recipe : RecipeShort
{
[JsonProperty]
private List<Ingredient> ingredients;
[JsonProperty]
public string Method { get; set; }
}
Recipe res = new Recipe
{
Id = "123",
Title = "Text",
Method ="Text",
Ingredients = ingredients
};
I've tried several ways but it did not work.
One way:
string str1 = Newtonsoft.Json.JsonConvert.SerializeObject(res, typeof(RecipeShort),null);
Other way:
RecipeShort temp = (RecipeShort) res;
string str1 = Newtonsoft.Json.JsonConvert.SerializeObject((RecipeShort)temp, typeof(RecipeShort),null);
The third way:
string str = Newtonsoft.Json.JsonConvert.SerializeObject(res);
RecipeShort temp1 = Newtonsoft.Json.JsonConvert.DeserializeObject<RecipeShort>(str);
string str1 = Newtonsoft.Json.JsonConvert.SerializeObject(temp1, typeof(RecipeShort),null);
First two ways are fully serialize the object. The third fails on attempt to deserialize with NullPointerExeption.
Is there any elegant way to serialize only the base class without doing it manually?
You can probably use IContractResolver, see https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm.
Related
This question already has answers here:
Deserializing JSON with dynamic keys
(4 answers)
Complicated Json to C# Object Deserialize with classes
(2 answers)
Using JSON.NET to read a dynamic property name
(1 answer)
Closed 10 months ago.
I'm having an issue with JSON that I'm getting back for a hotel booking API. Essentially I'm taking the output and trying to create a class so that I can put it into an object. The problem is this: The JSON is returning objects and we can't readily use this format to make a C# class because of how it's formatted:
Example of how the JSON is formatted
Here is a snippet of it. Attributes is the highest level, then "pets" is next. The values we need for this are id: 5058 and name: Service Animals are allowed, however they are creating this "5058" and "5059" and "2050" object which is making it difficult to create a class and properly deserialize it.
I'm fairly new at C# (formerly long-time C programmer), so trying to understand the best way to make a class for something like this where the "5058" is not actually created as a class ... I would prefer if we could ingest that level into an array or list perhaps?
This is what something like json2csharp.com outputs...
public class Pets
{
public _5058 _5058 { get; set; }
public _5059 _5059 { get; set; }
public _2050 _2050 { get; set; }
}
And then
public class _5059
{
public string id { get; set; }
public string name { get; set; }
}
5059 should not be a class... That appears to be the name of the object; I want to ignore that because the ID: in the object is 5059
This wont work since there are thousands of IDs, and we're not looking to create a separate class for each ID -
I would like to make a class more like this
public class Pets
{
public string id { get; set; }
public string name {get; set; }
}
This is how I'm receiving the JSON
{
"pets":{
"5058":{
"id":"5058",
"name":"Service animals are allowed"
},
"5059":{
"id":"5059",
"name":"Service animals are exempt from fees/restrictions"
},
...
}
}
(This is a small snippet)
Again, here, they have "5059":{"id":"5059","name":"Service animals...."
So, what's the best way to ingest this with a class in C# without creating classes for the ID, the way a JSON to C# class creator would do?
Thanks for you help
That looks like a Dictionary<string, Pet> where those 5058, 5059, etc. are the keys.
public class Data
{
public Dictionary<string, Pet> pets { get; set; }
}
public class Pet
{
public string id { get; set; }
public string name { get; set; }
}
Deserialize the json as below
var data = JsonSerializer.Deserialize<Data>(json);
or if you're using Newtonsoft.Json
var data = JsonConvert.DeserializeObject<Data>(json);
This question already has answers here:
How to exclude a property from being serialized in System.Text.Json.JsonSerializer.Serialize() using a JsonConverter
(5 answers)
System.Text.Json API is there something like IContractResolver
(2 answers)
Closed 2 years ago.
Question
Can I dynamically ignore a property from a sealed class using System.Text.Json.JsonSerializer?
Example Code
Example class from another library:
public sealed class FrozenClass
{
// [JsonIgnore] <- cannot apply because I don't own this class
public int InternalId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Default Serialization:
var person = new FrozenClass() { InternalId = 3, FirstName = "Dorothy", LastName = "Vaughan" };
var jsonString = System.Text.Json.JsonSerializer.Serialize(person);
Actual Outcome:
{ "InternalId": 3, "FirstName": "Dorothy", "LastName": "Vaughan" }
Expected Outcome:
{ "FirstName": "Dorothy", "LastName": "Vaughan" }
Alternatives that don't work
There are two other questions on how to add JsonIgnore at RunTime & add dynamic property name for serialization, but both are targeted at Newtonsoft's Json.NET - and often reference this extension method
There are several ways to modify the way a class is serialized with the native JsonSerializer, but all seem to rely on modifying the underlying class:
You can exclude properties from serialization by adding the [JsonIgnore] attribute to the original class
You can register a JsonConverter on a property by adding the [JsonConverter] attribute to the original class
However, in my case, the class is from another library and cannot be extended
Workarounds
A possible workaround is to create another exportable class and setup a mapper between them
public class MyFrozenClass
{
public MyFrozenClass(FrozenClass frozen)
{
this.FirstName = frozen.FirstName;
this.LastName = frozen.LastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
var jsonString = System.Text.Json.JsonSerializer.Serialize(new MyFrozenClass(person));
This question already has answers here:
How to exclude property from Json Serialization
(9 answers)
Closed 5 years ago.
How to JsonConvert.SerializeObject after object cast?
I have two classes like this example, and I want my serialized json to not include the "Id" field.
public class Person : Description
{
public int Id { get; set; }
}
public class Description
{
public string Name { get; set; }
}
Person person = new Person() { Id = 1, Name = "Bill" };
Description description = person;
string jsonDescription = JsonConvert.SerializeObject(description);
Console.WriteLine(jsonDescription);
// {"Id":1,"Name":"Bill"}
I've tried several things like casting with "as" or casting with .Cast() but no luck yet.
Thank you for your suggestions.
Just use the JsonIgnore attribute.
public class Person : Description
{
[JsonIgnore]
public int Id { get; set; }
}
This question already has answers here:
NewtonSoft add JSONIGNORE at runTime
(7 answers)
Closed 5 years ago.
I have a class of which I serialize objects to JSON using json.net. The class has some property that I usually didn't want serialized, so I marked it with JsonIgnore.
public class SomeClass
{
[JsonIgnore]
public int ID { get; set; }
public int SecondID { get; set; }
public string Name { get; set; }
}
Now, in a different context, I wish to export objects of the same class, but here I wish to also export the ID (that I have flagged to be ignored in the first context).
Is it possible to dynamically flag a property to be ignored before serializing to JSON or do I have to write a custom serializer to achieve this?
How can I achieve the desired behavior in the simplest possible way?
Here you can make a list of properties you want to ignore :
[JsonIgnore]
public List<Something> Somethings { get; set; }
//Ignore by default
public List<Something> Somethings { get; set; }
JsonConvert.SerializeObject(myObject,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
I am trying to get values from Json objects that all are formed like this one:
http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=4798
I tried several libraries but none of them resulted in the way I wanted. I want to put the values into specific Datamembers.
This was my last attempt, it runs but it seems like my Datamembers are not getting any values.
namespace JSON_Data
{
public partial class Form1 : Form
public Form1()
{
InitializeComponent();
string jsonString = #"{""item"":{""icon"":""http://services.runescape.com/m=itemdb_rs/4996_obj_sprite.gif?id=4798"",""icon_large"":""http://services.runescape.com/m=itemdb_rs/4996_obj_big.gif?id=4798"",""id"":4798,""type"":""Ammo"",""typeIcon"":""http://www.runescape.com/img/categories/Ammo"",""name"":""Adamant brutal"",""description"":""Blunt adamantite arrow...ouch"",""current"":{""trend"":""neutral"",""price"":305},""today"":{""trend"":""neutral"",""price"":0},""members"":""true"",""day30"":{""trend"":""positive"",""change"":""+2.0%""},""day90"":{""trend"":""positive"",""change"":""+8.0%""},""day180"":{""trend"":""positive"",""change"":""+23.0%""}}}";
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Item));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
Item obj = (Item)ser.ReadObject(stream);
}
}
}
This is how my class "Item" looks
namespace JSON_Data
{
[DataContract]
public class Item
{
[DataMember]
public string Icon { get; set; }
[DataMember]
public string Icon_large { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public string Members { get; set; }
}
}
if you can try the Newtonsoft i can provide a way.. its very good and better approach as far as i think
var ob = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonString);
Item a = ((JObject)ob["item"]).ToObject<Item>();
There are several JSON serializers you can use in C#. Some have better performance, some have better fault tolerance and others have circular reference treatments.
In your case, I see that you simply want an object without passing it (to a WCF) anywhere. You can follow the second answer of this question: Deserialize JSON into C# dynamic object? Example code copied from that answer:
dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = stuff.Name;
string address = stuff.Address.City;
A dynamic object in C# allows you to read a property without declaring a class for it.