JSON Deserialization of Cast object returns Uncast JSON
By : rishith
Date : March 29 2020, 07:55 AM
I hope this helps you . Just because you have assigned a B to an A does not mean that it is no longer a B. You can see this for yourself if you print out the type of your InstanceA variable after the assignment: code :
B instanceB = new B() { PropA = "A", PropB = "B" };
A instanceA = instanceB;
Console.WriteLine(instanceA.GetType().Name);
public class BaseTypeConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
T instance = (T)value;
JObject obj = new JObject();
foreach (PropertyInfo prop in typeof(T).GetProperties())
{
if (prop.CanRead)
{
obj.Add(prop.Name, JToken.FromObject(prop.GetValue(instance)));
}
}
obj.WriteTo(writer);
}
public override bool CanRead
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
B instanceB = new B() { PropA = "A", PropB = "B" };
// serialize B, but only include the properties from type A
string json = JsonConvert.SerializeObject(instanceB, new BaseTypeConverter<A>());
Console.WriteLine(json);
{"PropA":"A"}
|
Json Deserialization and printing non-primitive object using c# and ASP.NET MVC and JSON.NET
By : hossein seyed bagher
Date : March 29 2020, 07:55 AM
may help you . Using Json.Net you can do something like this(it should also work with the JavaScriptSerializer) : code :
var ReadJson = System.IO.File.ReadAllText(@"E:\C# Learning\POI.json");
RootObject json = JsonConvert.DeserializeObject<RootObject>(ReadJson);
foreach (var item in json.poi)
{
Console.WriteLine("name: {0}, shorttext : {1}, Latitutde: {2} , Latitutde: {3}, Image: {4}", item.Name, item.Shorttext, item.GeoCoordinates.Latitude, item.GeoCoordinates.Longitude, string.Join(" ", item.Images));
}
|
Json Deserialization parsing non valid Json object
By : Lauren Nguyen Cohen
Date : March 29 2020, 07:55 AM
With these it helps You need to JArray results = JArray.Parse(token2["d"].ToString()); Please try code :
WebClient wc = new WebClient();
// Downloading & Deserializing the Json file
var jsonMain = wc.DownloadString("http://api.flexianalysis.com/services/FlexiAnalysisService.svc/FlexiAnalysisNews?key=gZ_lhbJ_46ThmvEki2lF&catagory=Forex");
JObject token2 = JObject.Parse(jsonMain);
JArray results = JArray.Parse(token2["d"].ToString());
List<News> listNews = new List<News>();
foreach (var result in results)
{
news = new News();
news.id = (string)result["ID"];
news.Title = (string)result["Title"];
news.Date = (string)result["PublishingDate"];
news.Content = (string)result["News"];
listNews.Add(news);
}
return View(listNews);
|
Retrieve(deserialize) a specific property from a json object to a C# struct (json deserialization)
By : tolecnal
Date : March 29 2020, 07:55 AM
it helps some times Here you go. It works perfect. First download "newtonsoft.json" from Nuget and add it to your project. Struct myStruct is your deserialized json object converted to a struct. code :
public void DeserializeMyJsonObject()
{
string json;
using (StreamReader r = new StreamReader("d:\\json.txt"))
{
json = r.ReadToEnd();
}
var myStruct = JsonConvert.DeserializeObject<YourStruct>(json);
}
public struct YourStruct
{
[JsonProperty("params")]
public List<Object> KeyAndProperties { get; set; }
}
|
How to do custom JSON serialization and deserialization in C#, when the object does not match the JSON
By : user3487267
Date : March 29 2020, 07:55 AM
Hope this helps You can use Newtonsoft JSON. First, add JsonProperty attributes to your classes: code :
public class ClassA
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("objects")]
public ClassB[] Objects { get; set; }
}
public class ClassBConverter : JsonConverter<ClassB> {
...
public override void WriteJson(JsonWriter writer, ClassB value, JsonSerializer serializer)
{
writer.WriteValue((int)value.SomeEnum);
}
public override ClassB ReadJson(JsonReader reader, Type objectType, ClassB existingValue, bool hasExistingValue, JsonSerializer serializer)
{
int i = (int)((long) reader.Value);
return new ClassB { SomeEnum = i };
}
}
JsonConvert.(De)SerializeObject<ClassA>(yourJSONString, new ClassBConverter());
|