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.
Related
Is there a way to deserialize an integer into a string ? I need it for compatibility reason.
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Abc.Test
{
[JsonSerializable(typeof(OrderInfo), GenerationMode = JsonSourceGenerationMode.Metadata)]
public partial class OrderInfoContext : JsonSerializerContext
{ }
public partial class OrderInfo
{
public string UserReference { get; set; }
}
public class Program
{
static void Main(string[] args)
{
var json = #"{""UserReference"": 123}"; // <---- how having 123 deserialize as a string?
var s = JsonSerializer.Deserialize(json, OrderInfoContext.Default.OrderInfo);
}
}
}
In some cases it can make sense to separate your serialization objects (aka DTOs) from your domain objects. This give you several benefits:
Allow your domain objects to have behavior defined, without affecting serialization.
A place to handle any complicated changes to the model without losing backwards compatibility.
Allow the serialization objects to fulfill requirements like public setters, without affecting the usage in the rest of the code.
Ex:
public class OrderInfoDTO
{
public int UserReference { get; set; }
public OrderInfo ToModel() => new OrderInfo(UserReference.ToString();
}
public class OrderInfo{
public string UserReference {get;}
public OrderInfo(string userReference) => UserReference = userReference;
}
You can use a custom converter on a property. I'll look something like:
public partial class OrderInfo
{
[JsonConverter(typeof(YourCustomConverter))]
public string UserReference { get; set; }
}
Below is the format of post request expected in JSON. Can anyone please tell me how to achieve this.
{
"MywebServiceInputDetail":{
"MyDatalst":{
"MyData":[
{
"name":"TestName",
"id":"2611201",
"SomeRefVal":"REF123456"
}
]
}
}
}
I am using JavaScriptSerializer as of now.
Below is the code.
[Serializable]
public struct MyStruct
{
public string name;
public string id;
public string refno;
}
JavaScriptSerializer jss = new JavaScriptSerializer();
string serializedJson = jss.Serialize(ObjMystrcut);
Above code results in the JSON string as
{"name":"TestName","id":"1234567","refno":"567123"}
I am new to JSON so I'm not able to formulate the request format.
I am avoiding to achieve it by hardcoding a json string. Basically, I am trying to understand what does { and [ bracketing mean. Does [ mean that I need to create an array of objects?
You can do something like this:
string serializedJson = jss.Serialize(new { MywebServiceInputDetail = new { MyDatalst = new { MyData = new[] { ObjMystrcut } } } });
{} is object notation, so it represents an object, with properties.
[] is an array notation.
Yes, the [ and ] symbols represent JSON arrays (collections of objects). In your example, MyData is a collection of those structs you created.
You need to create the following classes:
public class MywebServiceInputDetail
{
public MyDatalst MyDatalst { get; set; }
}
public class MyDatalst
{
public List<MyStruct> MyData { get; set; }
}
public struct MyStruct
{
public string name;
public string id;
public string SomeRefVal;
}
Now create a MywebServiceInputDetail object and serialize it.
Personally I would forget about using a struct and just create the following class instead:
public class MyClass
{
public string Name { get; set; }
public string Id { get; set; }
public string SomeRefVal { get; set; }
}
You should also add JSON attributes to the properties to make sure Name and Id are serialized with lowercase letters.
I am trying to understand why I am getting null values for the following:
Json:
{
"IdentityService": {
"IdentityTtlInSeconds": "90",
"LookupDelayInMillis": "3000"
}
}
Class:
public class IdentityService
{
public string IdentityTtlInSeconds { get; set; }
public string LookupDelayInMillis { get; set; }
}
Called with :
_identityService = JsonConvert.DeserializeObject<IdentityService>(itemAsString);
The class is instantiated but the values for IdentityTtlInSeconds and LookupDelayInMillis are null. I cannot see why they should be
You need one more class - an object which has one property called IdentityService:
public class RootObject
{
public IdentityService IdentityService { get; set; }
}
You need this class because JSON that you have has one property called IdentityService, and this object has two properties, called IdentityTtlInSeconds and LookupDelayInMillis. If you are using a default serializer your classes need to reflect the structure that you have in your JSON string.
And now you can use it to deserialize your string:
var rootObject = JsonConvert.DeserializeObject<RootObject>(itemAsString);
_identityService = rootObject.IdentityService;
I have a JSON string like:
var json = "{\"Attributes\": {\"name\":\"S1\", \"quantity\":\"100\"}}";
I want to design a class for the same; how does one approach while creating a class for JSON string in C# ?
If you are using Visual Studio 2012, go in the menu to EDIT -> Paste Special -> Paste JSON As CLasses.
You valid JSON should probably look like this (you should remove the \ before copying it to the clipboard):
{"Attributes": {"name":"S1", "quantity":"100"}}
The generated classes:
public class Rootobject
{
public Attributes Attributes { get; set; }
}
public class Attributes
{
public string name { get; set; }
public string quantity { get; set; }
}
Sample usage (note that the \ is still here, in order to have valid code syntax):
var json = "{\"Attributes\": {\"name\":\"S1\", \"quantity\":\"100\"}}";
var json_serializer = new JavaScriptSerializer();
Rootobject dc = json_serializer.Deserialize<Rootobject>(json);
You're question's unclear, but I assume you mean parsing JSON in to C# objects? Using JSON.NET and something like this can do that:
public class Attributes
{
[JsonProperty("name")]
public String Name { get; set; }
[JsonProperty("quantity")]
public Int32 Quantity { get; set; }
}
public class MyObject
{
[JsonProperty("Attributes")]
public Attributes Attributes { get; set; }
}
var myObj = JsonConvert.DeserializeObject<MyObject>(json);
Or you can go more broadly and let JSON.NET do it for you:
var obj = JsonConvert.DeserializeObject<dynamic>(
"{ \"Attributes\": {\"name\":\"S1\", \"quantity\":\"100\"}}"
);
Console.WriteLine(obj.Attributes["name"]) // S1
Console.WriteLine(obj.Attributes["quantity"]) // 100
have a look at the namespace System.Runtime.Serialization, you can find useful classes for (de)serializing JSON there
also you can read this similar question (searching before posting does not really hurt):
How do I represent this complex json document as a C# object?
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"));