I am getting response in json like this
data={"Id": "234", "Name": "pinky", "MobileNumber": "", "ClassName": "Class1_Physics", "DOBTime": "1990-04-11 15:46:38", "Landline": "", "Status": "Unmarried"}
I want to deserilize json and insert into table.
I have created 2 classes for it and using dll of Newtonsoft for deserilization.
public class JsonResult
{
public string Id { get; set; }
public string Name { get; set; }
public string MobileNumber { get; set; }
public string ClassName { get; set; }
public string DOBTime { get; set; }
public string Landline { get; set; }
public string Status { get; set; }
}
public class JsonResultRoot
{
[JsonProperty(PropertyName = "data")]
public string Data { get; set; }
public JsonResult JsonResult
{
get { return JsonConvert.DeserializeObject<JsonResult>(Data); }
}
}
Code :
decodedUrl : store actual json data/string
var JsonData = JsonConvert.DeserializeObject(decodedUrl).JsonResult;
If your JSON contains this data= part, then it is invalid JSON. You cannot deserialize it using JSON.NET library.
In order to deserialize this, you can simply clean this part out:
public class JsonResult
{
public string Id { get; set; }
public string Name { get; set; }
public string MobileNumber { get; set; }
public string ClassName { get; set; }
public string DOBTime { get; set; }
public string Landline { get; set; }
public string Status { get; set; }
}
// Usage:
jsonString = jsonString.Replace("data=").Trim();
var jsonObject = JsonConvert.DeserializeObject<JsonResult>(jsonString);
Of course, in general it looks bad. You should only do it if "you are getting response in json like this" and you can do nothing about it.
If there is any possibility to make incoming format correct, then better do it.
Related
I am trying to create a small asmx service with a method which will return some dummy data. I get the following error when I run the service:
"System.InvalidOperationException: System.Xml.XmlAttribute cannot be used as: 'xml element'."
My web method is as follows:
[WebMethod]
public SubmitCaseRequestResponse1 SubmitCaseRequest(SubmitCaseRequestRequest1 request)
{
var response = new SubmitCaseRequestResponse1
{
ResponseID = "456325898",
Success = true,
ValidationErrors = null
};
return response;
}
My SubmitCaseRequestResponse1 class:
public class SubmitCaseRequestResponse1
{
public string ResponseId { get; set; }
public bool Success { get; set; }
public ValidationError[] ValidationErrors { get; set; }
}
and the request class is :
public class SubmitCaseRequestRequest1
{
public AuthHeader AuthHeader { get; set; }
public SubmitCaseRequestRequest PostCaseDateRequest { get; set; }
}
I was supposed to serialize the complex type SubmitCaseRequestRequest1 and SubmitCaseRequestResponse1 . Needed to add [XmlElement] for the complex types and [XmlAttribute] for simple types
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://tempuri.org/")]
[Serializable]
public class SubmitCaseRequestRequest1
{
[XmlElement]
public AuthHeader AuthHeader { get; set; }
[XmlElement]
public SubmitCaseRequestRequest PostCaseDateRequest { get; set; }
}
[Serializable]
public class SubmitCaseRequestRequest
{
[XmlElement]
public Guid? RequestId { get; set; }
[XmlAttribute]
public string LCICourtNumber { get; set; }
[XmlAttribute]
public string CaseNumber { get; set; }
[XmlAttribute]
public string DebtorLastName { get; set; }
[XmlAttribute]
public string DateType { get; set; }
}
I have to post this javascript object to asp.net controller:
The model in server side is:
public class UserExperience
{
public class competences
{
public string id { get; set; }
public string level { get; set; }
public string name { get; set; }
public bool isNew { get; set; }
public bool isSaved { get; set; }
}
public long id { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string projectName { get; set; }
public string company { get; set; }
public string customerIndustry { get; set; }
public string jobTitle { get; set; }
public string projectDescription { get; set; }
public string responsabilities { get; set; }
public List<competences> competence { get; set; }
public List<int> deletedCompetences { get; set; }
public bool isNew { get; set; }
public bool isSaved { get; set; }
}
I tried to send the json like this:
$.ajax("/candidate/saveUserExperience", {
data : JSON.stringify({ue: is.Candidate.BO.userExperience[id]}),
//dataType: "text",
contentType : "application/json",
type : 'POST'
})
And this is the controller where I receive it:
public JsonResult saveUserExperience(UserExperience ue)
{
bool success;
success = true;
return Json(new { success, ue }, JsonRequestBehavior.AllowGet);
}
And I receive a null object.
I tried to do with:
UserExperience userExperience = new JavaScriptSerializer().Deserialize<UserExperience>(ue);
and I do not receive the competence subclass object.
Is there a solution to this problem ?
Thanks.
Why are you trying to pass is.Candidate.BO.userExperience[id] when you expect UserExperience object? Just write data: ue in ajax call parameters,
I keep getting a property set to null when I try to deserialize json which contains a toString name for a property
{
"field": "status",
"fieldtype": "jira",
"from": "10000",
"fromString": "Impeded",
"to": "10006",
"toString": "Review"
}
I tried with and without the following JsonProperty
public class ChangelogItem
{
public string field { get; set; }
public string fieldtype { get; set; }
public string from { get; set; }
public string fromString { get; set; }
public string to { get; set; }
//[JsonProperty(PropertyName = "toString")]
//public string newString { get; set; }
public string toString { get; set; }
}
but I keep getting a null value.
Any idea?
The following works fine for me with Json.Net v6.0.3:
public class ChangelogItem
{
public string field { get; set; }
public string fieldtype { get; set; }
public string from { get; set; }
public string fromString { get; set; }
public string to { get; set; }
public string toString { get; set; }
}
Test program:
class Program
{
static void Main(string[] args)
{
string json = #"
{
""field"": ""status"",
""fieldtype"": ""jira"",
""from"": ""10000"",
""fromString"": ""Impeded"",
""to"": ""10006"",
""toString"": ""Review""
}";
ChangelogItem item = JsonConvert.DeserializeObject<ChangelogItem>(json);
Console.WriteLine(item.toString);
}
}
Output:
Review
My Code works fine when calling REST URL:
http://api.feedzilla.com/v1/categories.json
but when I call following URL I get error:
http://api.feedzilla.com/v1/categories/15/articles.json?count=36&since=2012-11-15&client_source=&order=relevance&title_only=0&
Error:
{"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.IEnumerable`1[Nitin.News.DAL.Resources.Article]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'articles', line 1, position 12."}
My Code is as follows:
public class Article
{
public string publish_date { get; set; }
public string source { get; set; }
public string source_url { get; set; }
public string summary { get; set; }
public string title { get; set; }
public string url { get; set; }
}
public IEnumerable<Article> Get()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://api.feedzilla.com/v1/");
//Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// call the REST method
HttpResponseMessage response = client.GetAsync("http://api.feedzilla.com/v1/categories/2/articles.json??count=36&since=2012-11-15&client_source=&order=relevance&title_only=0&").Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
return response.Content.ReadAsAsync<IEnumerable<Article>>().Result;
//wont work
//string JSON =response.Content.ReadAsStringAsync().Result;
//return JsonConvert.DeserializeObject<IEnumerable<T>>(JSON);
}
else
{
throw new Exception(string.Format("Data access faild,{0} ({1}) method:{2}", (int)response.StatusCode, response.ReasonPhrase, MethodURL));
}
}
You need another level in your object hierachy... i.e. a root to contain the IEnumerable.
Runing the JSON into the tool at http://json2csharp.com/ generates the following proxy classes:
public class Enclosure
{
public int length { get; set; }
public string media_type { get; set; }
public string uri { get; set; }
}
public class Article
{
public string author { get; set; }
public string publish_date { get; set; }
public string source { get; set; }
public string source_url { get; set; }
public string summary { get; set; }
public string title { get; set; }
public string url { get; set; }
public List<Enclosure> enclosures { get; set; }
}
public class RootObject
{
public List<Article> articles { get; set; }
public string description { get; set; }
public string syndication_url { get; set; }
public string title { get; set; }
}
You just need to change your code to this then:
// Parse the response body. Blocking!
return response.Content.ReadAsAsync<RootObject>().Result.articles;
Obviously strip out any properties you dont need. Just thought I would show them all out of interest.
I got null value for byte array in json web service when deserializing.but it returns byte array when invoked from browser.
C# Code:
var url = re.DownloadString("XXXX/ListService.svc/lstFooddtl/1/21");
var a = JsonConvert.DeserializeObject<FooddtlResult>(url);
In a i got null for food_photo...when i deserialize...
c# Class:
public class photo
{
public byte[] food_photo { get; set; }
}
public class Food
{
public int food_id { get; set; }
public string food_name { get; set; }
public photo[] food_photo { get; set; }
public string unitcost { get; set; }
}
public class FooddtlResult
{
public Food[] Result { get; set; }
}
{"Result":[{"food_id":"61","food_name":"Idli","food_photo":[255,216,255,224,0,....217],"unitcost":null}]}
Your model does not match the JSON. For correct deserialization change your Food class to
public class Food
{
public int food_id { get; set; }
public string food_name { get; set; }
public byte[] food_photo { get; set; }
public string unitcost { get; set; }
}
and remove the photo class.
Otherwise, if you want to keep the model structure, then correct JSON should be:
{"Result":[{"food_id":"61","food_name":"Idli","food_photo":[{"food_photo":[255,216,255,224,0,....217]},{"food_photo":[255,...]},...],"unitcost":null}]}