I have a json object and I am trying to convert it to my c# object. Here is my JSON:
{"GuvenlikNoktaArray": {"GuvenlikNoktası": [{"Id": 1,"GuvenlikNoktası1":"SANTIYE","KartNo":"000001889174217","Sira": 1},{"Id": 2,"GuvenlikNoktası1":"INSAAT","KartNo":"000000803567858","Sira": 2},{"Id": 3,"GuvenlikNoktası1":"ÇALISMA","KartNo":"000003417926233","Sira": 3},{"Id": 4,"GuvenlikNoktası1":"GÜVENLIK","KartNo":"000001888909897","Sira": 4}]}}
And my c# class:
public partial class GuvenlikNoktası
{
public GuvenlikNoktası()
{
this.GüvenlikNoktasıOlay = new HashSet<GüvenlikNoktasıOlay>();
this.PanikButonuAlarmlari = new HashSet<PanikButonuAlarmlari>();
}
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public string Sira { get; set; }
public virtual ICollection<GüvenlikNoktasıOlay> GüvenlikNoktasıOlay { get; set; }
public virtual ICollection<PanikButonuAlarmlari> PanikButonuAlarmlari { get; set; }
}
And last, my convert try:
public void AddIstasyon(string json_string)
{
GuvenlikNoktası result = new JavaScriptSerializer().Deserialize<GuvenlikNoktası>(json_string);
}
I don't get any errors but when I debuged, I see that all attributes inside 'result' are null. It seems like an empty object. How can I get a correct 'GuvenlikNoktası' object ? (Btw I am pretty sure I am getting the json object correctly).
If you must keep this JSON structure as-is you may use JObject to navigate inside your JSON properties until you reach your target objects to deserizlize. Please can you try the code below;
PS: This code uses Newtonsoft.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SO_39847703
{
class Program
{
static void Main(string[] args)
{
string json = "{\"GuvenlikNoktaArray\": {\"GuvenlikNoktası\": [{\"Id\": 1,\"GuvenlikNoktası1\":\"SANTIYE\",\"KartNo\":\"000001889174217\",\"Sira\": 1},{\"Id\": 2,\"GuvenlikNoktası1\":\"INSAAT\",\"KartNo\":\"000000803567858\",\"Sira\": 2},{\"Id\": 3,\"GuvenlikNoktası1\":\"ÇALISMA\",\"KartNo\":\"000003417926233\",\"Sira\": 3},{\"Id\": 4,\"GuvenlikNoktası1\":\"GÜVENLIK\",\"KartNo\":\"000001888909897\",\"Sira\": 4}]}}";
AddIstasyon(json);
}
public static void AddIstasyon(string json_string)
{
dynamic jsonObject = JObject.Parse(json_string);
string jsonToDeserializeStrongType = jsonObject["GuvenlikNoktaArray"]["GuvenlikNoktası"].ToString();
List<GuvenlikNoktası> result = JsonConvert.DeserializeObject<List<GuvenlikNoktası>>(jsonToDeserializeStrongType); ;
}
}
public partial class GuvenlikNoktası
{
public GuvenlikNoktası()
{
this.GüvenlikNoktasıOlay = new HashSet<GüvenlikNoktasıOlay>();
this.PanikButonuAlarmlari = new HashSet<PanikButonuAlarmlari>();
}
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public string Sira { get; set; }
public virtual ICollection<GüvenlikNoktasıOlay> GüvenlikNoktasıOlay { get; set; }
public virtual ICollection<PanikButonuAlarmlari> PanikButonuAlarmlari { get; set; }
}
public class GüvenlikNoktasıOlay
{
}
public class PanikButonuAlarmlari
{
}
}
Hope this helps
Your JSON data and your class definition do not fit together. Therefore the default values (NULL) are provided by the serializer.
In order to deserialize the given JSON data you need a class structure like:
public class Root
{
public LevelOne GuvenlikNoktaArray {get; set;}
}
public class LevelOne {
public IEnumerable<GuvenlikNoktası> GuvenlikNoktası {get; set;}
}
You can use this class.
public class GuvenlikNoktası
{
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public int Sira { get; set; }
}
public class GuvenlikNoktaArray
{
public IList<GuvenlikNoktası> GuvenlikNoktası { get; set; }
}
public class Example
{
public GuvenlikNoktaArray GuvenlikNoktaArray { get; set; }
}
You can use this link For your referencehttp://jsonutils.com/.
Related
I have a model like below:
public class YourInformationInputModel
{
public YourInformationInputModel()
{
PrimaryBuyerInformation = new PrimaryBuyerInformationInputModel();
}
public PrimaryBuyerInformationInputModel PrimaryBuyerInformation { get; set; }
public bool TermsCondition { get; set; }
}
PrimaryBuyerInputModel like below:
public class PrimaryBuyerInformationInputModel
{
[Required]
public string BuyerFirstName { get; set; }
public string BuyerMiddleInitial { get; set; }
[Required]
public string BuyerLastName { get; set; }
}
and when I am submitting my form then I am getting JSON like below:
{
"PrimaryBuyerInformation.BuyerFirstName": "Sunil",
"PrimaryBuyerInformation.BuyerMiddleInitial": "",
"PrimaryBuyerInformation.BuyerLastName": "Choudhary",
"TermsCondition": "true"
}
When I am trying to deserialize this json the TermsCondition property successfully done, but the property of PrimaryBuyerInformation is not mapped.
var myObject = JsonConvert.DeserializeObject<YourInformationInputModel>(json);
Any idea how to do that ?
Kindly take a cue from the code below, i tested it and you should be able to get your value as request. This solves the issue of you trying to access the property you have mapped in a dot property name format.
Instead your object should be nested in a curly brace showing that the other property belongs to PrimaryBuyerInformationInputModel which is another object entirely.
Best Regards,
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var json = #"{'PrimaryBuyerInformation': {'buyerFirstName': 'Sunil','buyerMiddleInitial': '','buyerLastName': 'Choudhary'},'termsCondition': false}";
var obj = JsonConvert.DeserializeObject<YourInformationInputModel>(json);
Console.WriteLine(obj.PrimaryBuyerInformation.BuyerFirstName);
}
}
public class YourInformationInputModel
{
public YourInformationInputModel()
{
PrimaryBuyerInformation = new PrimaryBuyerInformationInputModel();
}
public PrimaryBuyerInformationInputModel PrimaryBuyerInformation { get; set; }
public bool TermsCondition { get; set; }
}
public class PrimaryBuyerInformationInputModel
{
public string BuyerFirstName { get; set; }
public string BuyerMiddleInitial { get; set; }
public string BuyerLastName { get; set; }
}
JSON
{
"SoftHoldIDs": 444,
"AppliedUsages": [
{
"SoftHoldID": 444,
"UsageYearID": 223232,
"DaysApplied": 0,
"PointsApplied": 1
}
],
"Guests": [
1,
2
]
}
In the above JSON SoftholdIDs is integer and AppliedUsages is class array property in C# Model
Issue is --How we can map JSON to class property.
Class code
public class ReservationDraftRequestDto
{
public int SoftHoldIDs { get; set; }
public int[] Guests { get; set; }
public AppliedUsage[] AppliedUsages { get; set; }
}
public class AppliedUsage
{
public int SoftHoldID { get; set; }
public int UsageYearID { get; set; }
public int DaysApplied { get; set; }
public int PointsApplied { get; set; }
}
Tried below code for mapping
ReservationDraftRequestDto reservationDto = null;
dynamic data = await reservationDraftRequestDto.Content.ReadAsAsync<object>();
reservationDto = JsonConvert.DeserializeObject<ReservationDraftRequestDto>(data.ToString());
You need to change
dynamic data = await reservationDraftRequestDto.Content.ReadAsAsync<object>();
to
string data = await reservationDraftRequestDto.Content.ReadAsStringAsync();
this will read your response as string
then do
reservationDto = JsonConvert.DeserializeObject<ReservationDraftRequestDto>(data);
this work
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
string json = #"{""SoftHoldIDs"": 444,""AppliedUsages"": [ {""SoftHoldID"": 444,""UsageYearID"": 223232,""DaysApplied"": 0,""PointsApplied"": 1}],""Guests"": [ 1, 2]}";
Rootobject reservationDto = JsonConvert.DeserializeObject<Rootobject>(json.ToString());
Debug.WriteLine(reservationDto.SoftHoldIDs);
foreach (var guest in reservationDto.Guests)
{
Debug.WriteLine(guest);
}
}
}
public class Rootobject
{
public int SoftHoldIDs { get; set; }
public Appliedusage[] AppliedUsages { get; set; }
public int[] Guests { get; set; }
}
public class Appliedusage
{
public int SoftHoldID { get; set; }
public int UsageYearID { get; set; }
public int DaysApplied { get; set; }
public int PointsApplied { get; set; }
}
}
First create class copying json as classwith visualstudio.
Next you have double quote in json respons so deal with it.
Json.NET: Deserilization with Double Quotes
Hi I have a simple nested json and am trying to parse it with Javascriptserializer(). I created a class with properties and one more class for another nested data. But am not able to access full properties
I have tried the below code
This works well and below is my class where am saving this content
when i do
Please try below code.
I have tried with Newtonsoft.Json
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var jsonData ="{\"Command\":\"te\",\"Data\":{\"Image\":\"/6D/ogARAP8\",\"Imagetype\":\"FLS\",\"Imageformat\":\"bmp\",\"MissingFingers\":[\"FLIF\",\"FLMF\"]}}";
var jsonRootObject = JsonConvert.DeserializeObject<RootObject>(jsonData);
Console.WriteLine(jsonRootObject.Data.MissingFingers[0]);
Console.WriteLine(jsonRootObject.Data.Imagetype);
Console.WriteLine(jsonRootObject.Data.Image);
}
public class Data
{
public string Image { get; set; }
public string Imagetype { get; set; }
public string Imageformat { get; set; }
public List<string> MissingFingers { get; set; }
}
public class RootObject
{
public string Command { get; set; }
public Data Data { get; set; }
}
}
Like demo here
I have a xml format in following format mentioned below:-
<JobRunnerPluginStaus PluginName="JobRun">
<JobstepStatus>
<JobStatus StepNumber="1" StepStatus="Done"/>
<JobStatus StepNumber="2" StepStatus="Started" />
</JobstepStatus>
</JobRunnerPluginStaus>
I want to get it converted to following class object using Generics and Reflection.
I want to convert the attributes to simple type(PluginName) and the nested property to a list object(JobstepStatus).
public class JobRunnerPluginStaus
{
public List<JobStatus> JobstepStatus { get; set; }
public string PluginName { get; set; }
}
public class JobStatus
{
public int StepNumber { get; set; }
public string StepStatus { get; set; }
}
I mostly use sites like: https://xmltocsharp.azurewebsites.net/
to do the dirty work for me.
Below is how your class hierarchy would look like:
[XmlRoot(ElementName="JobStatus")]
public class JobStatus {
[XmlAttribute(AttributeName="StepNumber")]
public string StepNumber { get; set; }
[XmlAttribute(AttributeName="StepStatus")]
public string StepStatus { get; set; }
}
[XmlRoot(ElementName="JobstepStatus")]
public class JobstepStatus {
[XmlElement(ElementName="JobStatus")]
public List<JobStatus> JobStatus { get; set; }
}
[XmlRoot(ElementName="JobRunnerPluginStaus")]
public class JobRunnerPluginStaus {
[XmlElement(ElementName="JobstepStatus")]
public JobstepStatus JobstepStatus { get; set; }
[XmlAttribute(AttributeName="PluginName")]
public string PluginName { get; set; }
}
I hate some trouble sorting the data I recieve from a webresponse.
Right now they come in "random", and I haven't been able to sort it at all.
Right now the partial class looks like this:
namespace computers{
using System;
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
using J = Newtonsoft.Json.JsonPropertyAttribute;
public partial class GettingStarted
{
[J("devices")] public Device[] Devices { get; set; }
}
public partial class Device
{
[J("device_id")] public string DeviceId { get; set; }
[J("assigned_to")] public bool AssignedTo { get; set; }
[J("alias")] public string Alias { get; set; }
[J("description")] public string Description { get; set; }
[J("last_seen")] public string LastSeen { get; set; }
[J("remotecontrol_id")] public string RemotecontrolId { get; set; }
[J("groupid")] public string Groupid { get; set; }
[J("online_state")] public string OnlineState { get; set; }
[J("supported_features")] public string SupportedFeatures { get; set; }
}
public partial class GettingStarted
{
public static GettingStarted FromJson(string json) => JsonConvert.DeserializeObject<GettingStarted>(json, Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this GettingStarted self) => JsonConvert.SerializeObject(self, Converter.Settings);
}
public class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
};
}
As said before, the data comes in random and all my attempts at sorting them result in either a crash or does nothing.
Thanks in advance!
You can use lambda expressions to achieve this
Add using System.Linq directive
After you pupulate your 'Devices' array, use this to sort it:
Devices = Devices.OrderBy(x=>x.Alias).ToArray()