I'm using Newwtonsoft.JSON for build my json file, actually what I did is create different classes models, as this:
class GeneralModel
{
public string Language { get; set; }
}
and then for build the json file:
GeneralModel lsModel = new GeneralModel();
string json = JsonConvert.SerializeObject(lsModel);
File.WriteAllText(settingsFilePath, json);
this will create a json that contains Language, but I need to put in this json different classes, what I need is set an index that contains each class name, for example:
"GeneralModel": {
"Language" : "english"
},
"AnoherClassName": {
"ClassProperty" : value
}
how can I do this with Newtonsoft?
public class GeneralModel
{
public string Language { get; set; }
}
public class AnotherModel
{
public string AnotherProperty { get; set; }
}
public class SuperClass
{
public GeneralModel generalModel { get; set; }
public AnotherModel anotherModel { get; set; }
}
then
SuperClass s = new WMITest.SuperClass();
s.generalModel = new GeneralModel();
s.generalModel.Language = "language";
s.anotherModel = new AnotherModel();
s.anotherModel.AnotherProperty = "example";
string json = JsonConvert.SerializeObject(s);
Related
Hi i am not able to bind data in C# class fields..
getting error "Object reference not set to an instance of an object".
this is my C# Class as below:
public partial class AccessCodeReqBody
{
[JsonProperty("scenarioKey")]
public string ScenarioKey { get; set; }
[JsonProperty("destinations")]
public Destination[] Destinations { get; set; }
[JsonProperty("whatsApp")]
public WhatsApp WhatsApp { get; set; }
}
public partial class Destination
{
[JsonProperty("to")]
public To To { get; set; }
}
public partial class To
{
[JsonProperty("phoneNumber")]
public string PhoneNumber { get; set; }
}
public partial class WhatsApp
{
[JsonProperty("templateName")]
public string TemplateName { get; set; }
[JsonProperty("templateData")]
public string[] TemplateData { get; set; }
[JsonProperty("language")]
public string Language { get; set; }
}
& the request json as below:
{
"scenarioKey":"696BDB51C0ACF9E65B86D3E1D08A0084",
"destinations":[
{
"to":{
"phoneNumber":"919910666888"
}
}
],
"whatsApp":{
"templateName":"access_code",
"templateData":[
"Jennifer",
"Demo",
"123456"
],
"language":"en"
}
}
& the code for bind data in c# class as below where i am getting error on binding Phone number & template name :
AccessCodeReqBody reqbody = new AccessCodeReqBody();
reqbody.ScenarioKey = "51F5865AE296FAE86614EED";
reqbody.Destinations.To.PhoneNumber = text1;
reqbody.WhatsApp.TemplateName = "access_code";
reqbody.WhatsApp.Language = "en";
reqbody.WhatsApp.TemplateData = GetData(text2.ToString());
Thanks in Advance.
The structure of the classes is correct. use this code
AccessCodeReqBody accessCodeReqBody = JsonConvert.DeserializeObject<AccessCodeReqBody>(json);
Seems like a simple enough solution
AccessCodeReqBody reqbody = new AccessCodeReqBody();
reqbody.ScenarioKey = "51F5865AE296FAE86614EED";
// Initialize your WhatsApp object. It is null if you don't
reqbody.WhatsApp = new WhatsApp();
//reqbody.Destinations.To.PhoneNumber = text1;
reqbody.WhatsApp.TemplateName = "access_code";
reqbody.WhatsApp.Language = "en";
reqbody.WhatsApp.TemplateData = GetData(text2.ToString());
I have the following class which is populated after de-serializing a JSON string:
public class Doors
{
public List<Door> doors { get; set; }
}
public class Door
{
public int id { get; set; }
public string name { get; set; }
public bool elevator { get; set; }
}
JSON string:
var result = JsonConvert.DeserializeObject<Doors>(response.Content);
// "{\"doors\":[{\"id\":1,\"name\":\"Main Door\",\"elevator\":false},{\"id\":2,\"name\":\"Back Door\",\"elevator\":false}]}"
The data maps to my class fine, I'm then trying to pass the class data to another class:
public class WS4APIResult
{
public List<Door> doors { get; set; } = new List<Door>();
}
public class Door
{
public int id { get; set; }
public string name { get; set; }
public bool elevator { get; set; }
}
return new WS4APIResult() {
doors = result.doors
}
With the following error: any ideas please?
Cannot implicitly convert type 'System.Collections.Generic.List<WS4PortalApi.Models.Door>' to 'System.Collections.Generic.List<WS4PortalApi.Domain.Door>'
The two c#-Files refer to different classes if you type Door. You need to implement a conversion between WS4PortalApi.Models.Door and WS4PortalApi.Domain.Door.
Like:
public static WS4PortalApi.Domain.Door DoorConvert(WS4PortalApi.Models.Door door)
then you can use linq to generate a new List
doors = result.doors
.Select(d => DoorConvert(d))
.ToList();
You have to map the properties of your domain object to those of the model.
I normally create a method for this like:
var doors = new List<Model.Door>();
foreach(door in result.doors)
{
var doorModel = new Model.Door
{
id = door.id,
name = door.name,
elevator = door.elevator
};
doors.Add(doorModel);
}
return doors;
Or you can use a library like automapper.
I have a string stream returning JSON data from and API that looks like this:
"{\"Recs\":
[
{\"EID\":\"F67_24_6\",\"ReturnPeriod\":\"1\",\"GageStation\":\"NA\"},
{\"EID\":\"T67_24_6\",\"ReturnPeriod\":\"2.37\",\"GageStation\":\"Magueyes Island\"},
{\"EID\":\"R67_24_6\",\"ReturnPeriod\":\"1\",\"GageStation\":\"50147800\"}
]}"
I am trying to deserialize it to return this:
{"Recs":[
{"EID":"F67_24_6","ReturnPeriod":"1","GageStation":"NA"},
{"EID":"T67_24_6","ReturnPeriod":"2.37","GageStation":"Magueyes Island"},
{"EID":"R67_24_6","ReturnPeriod":"1","GageStation":"50147800"}
]}
I am using these public classes to structure the return:
public class New_Events_Dataset
{
public string EID { get; set; }
public string ReturnPeriod { get; set; }
public string GageStation { get; set; }
}
public class NewRootObject
{
public List<New_Events_Dataset> Reqs { get; set; }
}
When I try to apply this later, I basically get a return of {"Reqs":null}. What am I doing wrong here?
var jsonResponse = JsonConvert.DeserializeObject<NewRootObject>(strresult);
string json = new JavaScriptSerializer().Serialize(jsonResponse);
return json;
I think Reqs should be Recs:
public class NewRootObject
{
public List<New_Events_Dataset> Reqs { get; set; }
}
try:
public class NewRootObject
{
public List<New_Events_Dataset> Recs { get; set; }
}
Rename Reqs to Recs and create default constructor of class and instantiate Recs list
public class NewRootObject
{
List<New_Events_Dataset> Recs { get; set; }
public NewRootObject()
{
Recs = new List<New_Events_Dataset>();
}
}
Suppose we have class Request which we want to serialize to json and deserialize from json.
class Request {
public string SessionId { get; set; }
...
public string InnerJson { get; set; }
}
As json it should looks like
{
"SessionId": 1,
...
"InnerJson": {
"some": "json object",
"whatever": 666
}
}
InnerJson is some json document (arbitrary type).
Is it good to use string for InnerJson in Request?
Is there any good way to design Request class?
If you are going for a strongly typed model I'd suggest a factory. For demonstration sake:
public abstract class AbstractOptions { }
public class Options1 : AbstractOptions { public int Whatever { get; set; } }
public class Options2 : AbstractOptions { public string Some { get; set; } }
public class Options3 : AbstractOptions {
[JsonProperty("when")] public DateTime When { get; set; }
[JsonProperty("inner")] public InnerComplexObject Inner { get; set; }
}
public class Request {
[JsonProperty("session-id")] public string SessionId { get; set; }
[JsonProperty("options")] public AbstractOptions Options { get; set; }
}
public class InnerComplexObject { }
then use it like:
var req1 = new Request() { SessionId = "s1", Options = new Options1 { Whatever = 123 } };
var req2 = new Request() { SessionId = "s2", Options = new Options2 { Some = "some" } };
var req3 = new JToken.Request() { SessionId = "s3", Options = new Options3 { When = DateTime.UtcNow, Inner = new InnerComplexObject() } };
Otherwise, for flexibility, keep InnerJson a string and use dynamic queries.
I'm using the Json.Net Framework and I'm trying to convert multiple Json strings to different objects using only one method to achieve it.
To create the objects to store the Json data I'm using this website.
So far, I've managed to have one method to convert for one object (in this case RootObject) with the code bellow:
public class WebService
{
protected string jsonstring;
// Other code
// Method
public RootObject stringToObject(){
return JsonConvert.DeserializeObject<RootObject>(this.jsonstring);
}
}
// Object
public class RootObject
{
public string id { get; set; }
public string name { get; set; }
public string title { get; set; }
}
// Usage
WebService ws = new WebService ("http://example.com/json_string.json");
RootObject data = ws.stringToObject ();
The thing is that I have two more objects that I need to convert a Json string into:
public class RootObject2
{
public string id { get; set; }
public string menu_id { get; set; }
public string language { get; set; }
public string title { get; set; }
}
public class RootObject3
{
public string id { get; set; }
public string menu_id { get; set; }
public string position { get; set; }
public string active { get; set; }
}
I've tried to change the method return type to a generic type but it didn't work:
public object stringToObject(){
return JsonConvert.DeserializeObject<object>(this.jsonstring);
}
How can I have the method return type dynamic so I can do something like this:
WebService ws = new WebService ("http://example.com/json_string.json");
RootObject data = ws.stringToObject ();
WebService ws2 = new WebService ("http://example.com/json_string2.json");
RootObject2 data2 = ws2.stringToObject ();
WebService ws3 = new WebService ("http://example.com/json_string3.json");
RootObject3 data3 = ws3.stringToObject ();
Why not make your WebService be generic?
public class WebService<T>
{
protected string jsonstring;
// Other code
// Method
public T stringToObject(){
return JsonConvert.DeserializeObject<T>(this.jsonstring);
}
}
Then do
var ws = new WebService<RootObject>("http://example.com/json_string.json");
var data = ws.stringToObject ();
Or if you prefer, you can just make stringToObject be generic:
public class WebService
{
protected string jsonstring;
// Other code
// Method
public T stringToObject<T>(){
return JsonConvert.DeserializeObject<T>(this.jsonstring);
}
}
And do:
var data = ws.stringToObject<RootObject>();