Does Json.Encode() use JavaScriptSerializer Class to serialize - c#

Does the Json.Encode() Helper use the JavaScriptSerializer class to encode a string to json?
I am getting a circular reference exception when using Json.Encode(Model) even though my class properties that are being serialized have the [ScriptIgnore] attribute.
My only guess is that maybe the Json.Encode() helper doesn't use the JavaScriptSerializer to serialize to json but I can't find the documentation anywhere on msdn.
#Html.Raw(Json.Encode(Model))
Here's an example of one of the models that has a property that should not be serialized...
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Script.Serialization;
namespace RobotDog.Entities {
public class Character {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[MaxLength(200)]
public string Name { get; set; }
public virtual Person Person { get; set; }
[ScriptIgnore]
public virtual Movie Movie { get; set; }
}
}

Does the Json.Encode() Helper use the JavaScriptSerializer class to encode a string to json?
Yes.
From the source code:
private static readonly JavaScriptSerializer _serializer = Json.CreateSerializer();
public static string Encode(object value)
{
DynamicJsonArray dynamicJsonArray = value as DynamicJsonArray;
if (dynamicJsonArray != null)
return Json._serializer.Serialize((object) (object[]) dynamicJsonArray);
else
return Json._serializer.Serialize(value);
}
where JavaScriptSerializer is System.Web.Script.Serialization.JavaScriptSerializer
also to assist your issue see this thread

http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode(v=vs.111).aspx
according to the above link Json.Encode uses system.web.helpers.
What does your Model contain?
Also, are you sure that [ScriptIgnore] will ignore what you have it assigned to?

Related

JSON.NET: How to deserialize from specific json object to a class with a different name

This is driving me kinda nuts, because we don't have time to ask for the API team to change their response object name.
We have a json results that reads:
"seqRing": {
"admStatus": "disabled",
"status": null,
"lines": null
},
And I need that the json deserialization map it to this class:
public class SequentialRing
{
public string admStatus { get; set; }
public string status { get; set; }
public List<SeqLinesAttr> SeqLines { get; set; } = new List<SeqLinesAttr>();
}
If this were a case of a difference in the property name, I could simply use the JsonPropertyAttribute at the top of the property, but I need something similar for the class.
If there's something I could use? Please.
Thank you!
The JSON that you've shown has "seqRing" as a property of a larger JSON object. In order to deserialize that, you can create a wrapper class (or using an existing class) where you can specify the JSON property name for the class:
public class SequentialRingWrapper
{
[JsonProperty("seqRing")]
public SequentialRing SequentialRing { get; set; }
}

How can I serialize a RealmObject to JSON in Realm for Xamarin?

I need to serialize a deeply nested RealmObject to JSON for posting to a web api, using Xamarin with C#.
The reason for this is because I don't want the RealmObject properties to carry over, so really I'm looking for a POCO representation that I can serialize to JSON. I can't find any helper method in Realm for Xamarin to do this, so I'm guessing I need to roll my own.
I am considering a few options and was hoping for some feedback:
Use a JSON.NET Custom ContractResolver.
Including a ToObject method on the RealmObject that returns a dynamic type which I can then serialize using JsonConvert.SerializeObject
Using JsonTextWriter to iterate over the object and manually create the corresponding json.
At the moment I'm looking at option 2, as it's very straight forward e.g.
public class Person:RealmObject {
public string FirstName {get;set;}
public string LastName {get;set;}
public IList<Dog> Dogs {get;set;}
public dynamic ToObject(){
return new {FirstName,LastName, Dogs = Dogs.Select(x => x.ToObject())};
}
}
public class Dog {
public string Name;
public dynamic ToObject(){
return new {Name};
}
}
var person = new Person(){...}
var json = JsonConvert.SerializeObject(person.ToObject());
var content = new StringContent(json);
var response = await client.PostAsync(url, content);
Any thoughts?
If you don't mind applying a few attributes, a cleaner (in my mind) solution would be to use the JsonObject attribute with MemberSerialization.OptIn argument:
[JsonObject(MemberSerialization.OptIn)] // Only properties marked [JsonProperty] will be serialized
public class Person : RealmObject
{
[JsonProperty]
public string FirstName { get; set; }
[JsonProperty]
public string LastName { get; set; }
[JsonProperty]
public IList<Dog> Dogs { get; set; }
}

C# deserialization of JSON string with different property names

I'm having trouble deserializing a JSON string in C# to an object whose property names slightly differ from those in the JSON string. Here is my code:
using System.Collections.Generic;
using Newtonsoft.Json;
[JsonObject(MemberSerialization.OptIn)]
public class AuctionFilesList
{
[JsonProperty("files")]
public List<AuctionFile> Files { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class AuctionFile
{
#region Properties
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("lastModified")]
public long LastModified { get; set; }
#endregion
}
string jsonResponse = "{\"files\":[{\"url\":\"http://auction-
api.com/auctions.json\",\"lastModified\":1495397839000}]}"
AuctionFilesList auctionFiles = JsonConvert.DeserializeObject<AuctionFilesList>(jsonResponse);
I get no errors, it just fails to deserialize into the object. I have tried adding serializer settings as follows but it still fails:
JsonSerializerSettings jss = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
AuctionFilesList auctionFiles = JsonConvert.DeserializeObject<AuctionFilesList>(jsonResponse, jss);
My class structures agree with what json2csharp returns and it works when I match the property names of the object to the JSON, so either I am misunderstanding what JsonProperty does or it is being ignored somehow.
Any help is appreciated.

Deserialization of JSON in c#

I have the following JSON
{
"employee" : {
"property1" : "value1",
"property2" : "value2",
//...
}
}
to a class like
public class employee
{
public string property1{get;set;}
public string property2{get;set;}
//...
}
In my JSON if I need to add property3 then I need to make changes in my class too.
How can I deserialize to a class even though if I change my JSON(adding another property like property3).
The serialize/De-serialize techniques like newtonsoft.json is tightly coupled with the Class.
Is there a better way/tool to deserialize these kind of JSON in portable class in c#?
Newtonsoft is not tightly coupled with strong types. You can deserialize the dynamic types too. See the similar question here (How to read the Json data without knowing the Key value)
You can try .net's JavaScriptSerializer (System.Web.Script.Serialization.JavaScriptSerializer). If some field is added or removed it deserializes object normally.
namespace ConsoleApplication8
{
public class Person
{
public int PersonID { get; set; }
//public string Name { get; set; }
public bool Registered { get; set; }
public string s1 { get; set; }
}
class Program
{
static void Main(string[] args)
{
var s = "{\"PersonID\":1,\"Name\":\"Name1\",\"Registered\":true}";
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var o = serializer.Deserialize<Person>(s);
;
}
}
}
If we can use " Dictionary<string,string> employee" the above json can be deserilized.

deserialize json into .net object using json.net

I am having a problem deserializing some JSON string back into .net objects. I have a container class which contains some information from external and there is a field call ClassType which defined what type of information is that and the actual content is in another property, which currently can be anything, so we define that as an Object type.
Following are the .net class definition which helps to understand the issue.
class ClassOne
{
public string Name { get; set; }
public int Age { get; set; }
}
class ClassTwo
{
public string AddressLine { get; set; }
public string AddressLine2 { get; set; }
}
class ClassThree
{
public string Country { get; set; }
public string Passport { get; set; }
}
class ContainerClass
{
public string ClassType { get; set; }
public object ClassContent { get; set; }
}
When getting the information from external in a JSON format it will be something like:
{"ClassType":"Class1","ClassContent":{"Name":"James","Age":2}}
I am using Newtonsoft JSON.net library to deserialize the JSON string. It seems like that the default deserialize function will just deserialize that into an Newtonsoft.Json.Linq.JContainer. I just wondering how can I write some Converter to deserialize the ClassContent based on the ClassType definition. Any code sample will be highly appreciated.
I would go dynamic way, like:
string json = #"{""ClassType"":""Class1"",""ClassContent"":{""Name"":""James"",""Age"":2}}";
dynamic jObj = JObject.Parse(json);
if (jObj.ClassType == "Class1")
{
Console.WriteLine("{0} {1}", jObj.ClassContent.Name, jObj.ClassContent.Age);
}
Since returning an object (ClassContent) doesn't mean much, and you have to cast it to a concrete class somehow (using some if's or switch).
Sample:
var container = JsonConvert.DeserializeObject<ContainerClass>(json);
JContainer content = (JContainer)container.ClassContent;
switch(container.ClassType)
{
case "Class1": return container.ToObject(typeof(ClassOne));
..
}
use dynamic and call .ToObject(Type type)
dynamic root = JObject.Parse(json)
return root["ClassContent"].ToObject(Type.GetType(root["ClassType"]))
Try the following
var jsonObject = JObject.Parse(jsonString);
var result = jsonObject.ToObject(Type.GetType("namespace.className"));

Categories