I have some json data stored in a text file (the data is at https://github.com/VinceG/Auto-Cars-Makes-And-Models). I've run the json file through json2csharp which has generated the following classes for storage
public class Model
{
public string value { get; set; }
public string title { get; set; }
}
public class VehicleMake
{
public string value { get; set; }
public string title { get; set; }
public List<Model> models { get; set; }
}
I am trying to deserialise the data into the VehicleMake class using the following code
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Let's deserialise!");
var sb = new StringBuilder();
using (var sr = new StreamReader("models.json"))
{
string line;
while ((line = sr.ReadLine()) != null)
sb.AppendLine(line);
}
var vehicleList = Deserialize<VehicleMake>(sb.ToString());
Console.WriteLine("Done");
}
private static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
try
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception throw in Deserialize - {0}-{1}", ex.Message, ex.StackTrace);
return obj;
}
}
}
I've used this deserialize method in a number of different project and it has never caused an issue. Here though it is returning null into the vehicleList object.
The string builder.ToString() looks to contain all of the data (it is showing Other Yugo Models for the the final title which is correct)
I'm deliberately not using json.net as it's the only deserialisation of json I'm doing within this application and so it's somewhat overkill.
I should say that this isn't a homework project or anything like that
The json string represents an array, so you need to deserialize it to a List<VehicleMake>. Just change the following line:
var vehicleList = Deserialize<VehicleMake>(sb.ToString());
with:
var vehicleList = Deserialize<List<VehicleMake>>(sb.ToString());
You'll get a list of vehicles with properly initialized value, title and models properties.
You need to add [DataContract] and [DataMember] attributes to your class and members. Possibly also [Serializable]
using System;
using System.Runtime.Serialization;
[Serializable]
[DataContract]
public class Model
{
[DataMember(Name = "value")]
public string value { get; set; }
[DataMember(Name = "title")]
public string title { get; set; }
}
[Serializable]
[DataContract]
public class VehicleMake
{
[DataMember(Name = "value")]
public string value { get; set; }
[DataMember(Name = "title")]
public string title { get; set; }
[DataMember(Name = "models")]
public List<Model> models { get; set; }
}
Related
So basically I want to deserialize JSON data from sepcific URL to this class structure and then use it to display it on a page.
I don't understand how should I deserialize it because there are two classes that are compatible with JSON structure on the url.
This is the code shown below.
public class IndexModel : PageModel
{
public void OnGet()
{
Rootobject rootobject = new Rootobject();
rootobject.regions[0] = _download_serialized_json_data<Region>("https://visservice.meteoalarm.org/api/v1/regions?language=ATOM");
}
private static Region _download_serialized_json_data<Region>(string url) where Region : new()
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<Region>(json_data) : new Region();
}
}
public class Rootobject
{
public Region[] regions { get; set; }
}
public class Region
{
public bool active { get; set; }
public float[][] bb { get; set; }
public string code { get; set; }
public string name { get; set; }
}
}
Edit:
Value of json_data:
As per your class definitoins, it should be JsonConvert.DeserializeObject<Rootobject>(json_data)
In web service i am try to convert a jzonString to a list.
{
"name": "Test",
"Fname": "Testing",
"S1": "Content1",
"S2": "Content2",
"S3": "Content3"
}
[WebMethod]
public int Create(string Detils, string Companyid)
{
try
{
dynamic ScheduleShift = new JavaScriptSerializer().DeserializeObject(Detils);
\\ i need to set data to list or to an object
InvDetails objDetails = new InvDetails();
List<InvDetails> lstDetails = new List<InvDetails>();
return objDetails.CreateInvDetails(objDetils);
}
catch (Exception ex)
{
// Abort Transaction
throw ex;
}
}
Created another library file to declare the object and to insert into db
public class Inventory
{
CommonExecDAL CommonExecDAL = new CommonExecDAL();
public string name { get; set; }
public string Fname { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public int intCompanyId { get; set; }
public int CreateInvComputer(InvDetails objInvDetails)
{
SqlParameter[] arParms = new SqlParameter[6];
.........
}
}
If you don't want to create a class :
You can use JObject.Parse() method for deserializing dynamically.
As #SirRufo said, you can deserialize a JSON array into a list. but your JSON string in the sample is a single object!
Anyway, you deserialize JSON string to object with the use JSON.Net.
First, you have a class for Deserialize :
public class Data
{
public string name { get; set; }
public string Fname { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
}
Then you can deserialize JSON string to C# class :
var obj = JsonConvert.DeserializeObject<Data>(jsonString);
Just add reference to System.Web.Extensions ,(built in dll on .NET 4+) :
JavaScriptSerializer jss = new JavaScriptSerializer();
var jsonObj =jss.Deserialize<dynamic>(jsonString);
How can I convert this Class into XML ? Or is there any possible way I can convert a JSON String for the same class directly into XML ? I am not getting an idea or a sample code to start with the conversion.
public class Contacts
{
public Datum[] data { get; set; }
public Info info { get; set; }
}
public class Datum
{
public Owner Owner { get; set; }
public object Email { get; set; }
public string Description { get; set; }
public string currency_symbol { get; set; }
public string Mailing_Zip { get; set; }
}
public class Owner
{
public string name { get; set; }
public string id { get; set; }
}
public class Info
{
public int per_page { get; set; }
public int count { get; set; }
public int page { get; set; }
public bool more_records { get; set; }
}
Please help in converting the Class to XML or the JSON String based on the above class into an XML directly.
The scenario is that, I am receiving a JSON result from the API and this result needs to be processed in the SQL Server where the datatype has been kept as XML. I am hoping that this can be achieved successfully.
There are plenty of online resources to convert c# properties in to JSON or XML without any effort , try this and this and JSON to XML converter this too
Update
If you wish to convert inside the code try below. p.s (use Json.NET)
string json = //set your result JSON from the web API call;
XNode node = JsonConvert.DeserializeXNode(json, "Root");
Console.WriteLine(node.ToString());
this will convert your Json to XML
I solved the same converting the JSON to Class object and serializing the XML from the Class object.
public static string GetXMLFromObject(object o)
{
StringWriter sw = new StringWriter();
XmlTextWriter tw = null;
try
{
XmlSerializer serializer = new XmlSerializer(o.GetType());
tw = new XmlTextWriter(sw);
serializer.Serialize(tw, o);
}
catch (Exception ex)
{
//Handle Exception Code
}
finally
{
sw.Close();
if (tw != null)
{
tw.Close();
}
}
return sw.ToString();
}
I'm using the Newtonsoft library for parsing JSON:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
I have my json string and "MyClass" class.
JSON string:
{
"Result":
{
"MyClassList": [
{"Id":1,"Amount":"5,00"},
{"Id":2,"Amount":"10,00"},
{"Id":3,"Amount":"20,00"},
{"Id":4,"Amount":"25,00"}
]
"ReturnValues":
{
"ErrorCode":1,
"ErrorDescription":"Successful"
}
}
}
My Class:
public class MyClass
{
[JsonProperty("Id")]
Int64 Id { get; set; }
[JsonProperty("Amount ")]
string Amount { get; set; }
}
I am getting json data using these classes "GetMyClassList", "RootObject" and "ReturnValues".
List<MyClass> GetMyClassList()
{
JObject jo = new JObject();
List<MyClass> myClassList = new List<MyClass>();
jo.Add("Name", "Name");
jo.Add("Surname", "Surname");
url = "MyUrl";
string responseText = ExecuteHttpRequest(url , "POST",
"application/json", Encoding.UTF8.GetBytes(jo.ToString()), 3000);
myClassList = JsonConvert.DeserializeObject<RootObject>(responseText)
.GetMyClassListResult.MyClassList;
return myClassList;
}
public class ReturnValues
{
public int ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
public class GetMyClassListResult
{
[JsonProperty("MyClassList")]
public List<MyClass> MyClassList { get; set; }
public ReturnValues ReturnValues { get; set; }
}
public class RootObject
{
public GetMyClassListResult GetMyClassListResult { get; set; }
}
I cannot get this data array (Id and amount).
and I want to take this data and show it in a dataGridView.
The best way to t-shoot this is set breakpoint at the line, where u getting the results from method -> is it filled? This Line:
return myClassList;
I have run Your code with single adjustment -> I have just used the direct JSON (not from web) - code below. This run without issues and I can see all the results parsed out of the JSON.
You have to find if the issue is parsin the JSON, or setting the data to the DataGridTable (which code You have not included at all).
class Program
{
static void Main(string[] args)
{
var result = new Program().GetMyClassList();
foreach (var item in result)
Console.WriteLine($"ID: {item.Id}\tAmount:{item.Amount}");
Console.ReadKey();
}
public List<MyClass> GetMyClassList()
{
List<MyClass> myClassList = new List<MyClass>();
string responseText = "{\"GetMyClassListResult\":{\"MyClassList\":[{\"Id\":1,\"Amount\":\"5,00\"},{\"Id\":2,\"Amount\":\"10,00\"},{\"Id\":3,\"Amount\":\"20,00\"},{\"Id\":4,\"Amount\":\"25,00\"}],\"ReturnValues\":{\"ErrorCode\":1,\"ErrorDescription\":\"Successful\"}}}";
myClassList = JsonConvert.DeserializeObject<RootObject>(responseText)
.GetMyClassListResult.MyClassList;
return myClassList;
}
}
public class MyClass
{
[JsonProperty("Id")]
public Int64 Id { get; set; }
[JsonProperty("Amount")]
public string Amount { get; set; }
}
public class ReturnValues
{
public int ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
public class GetMyClassListResult
{
[JsonProperty("MyClassList")]
public List<MyClass> MyClassList { get; set; }
public ReturnValues ReturnValues { get; set; }
}
public class RootObject
{
public GetMyClassListResult GetMyClassListResult { get; set; }
}
I'm deserializing data received from a web-service.
The problem is that the deserialization of List returns an empty list and no exception are generated. Can you help me figure out why?
We have tried several possible syntax. The code below is the closest to the correct solution but we cannot deserialize correctly as a list of classes.
<ArrayOfBatch xmlns="http://schemas.datacontract.org/2004/07/myns" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<MaasBatch>
<BatchName>All Users</BatchName>
<Users>
<MaasUsers>
<firstName>bob</firstName>
<lastName>thetest</lastName>
<sourceEmail>bob#source.com</sourceEmail>
<sourceTenantID>111</sourceTenantID>
<targetEmail>bob#target.com</targetEmail>
<targetTenantID>222</targetTenantID>
</MaasUsers>
</Users>
</MaasBatch>
</ArrayOfBatch>
Code:
List<MAASBatch> lstMaasBatches = null;
try
{
string target = string.Empty;
using (var response = request.GetResponse())
{
Stream streamReader = response.GetResponseStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(List<MAASBatch>));
lstMaasBatches = (List<MAASBatch>)serializer.ReadObject(streamReader);
streamReader.Close();
}
return lstMaasBatches;
}
catch (Exception exc)
{
return lstMaasBatches;
}
Class:
[DataContract(Name = "MAASBatch", Namespace = "http://schemas.datacontract.org/2004/07/myns")]
[KnownType(typeof(MAASUsers))]
public class MAASBatch
{
[DataMember]
public string BatchName { get; set; }
[DataMember]
public List<MAASUsers> Users { get; set; }
[OnDeserializing]
internal void OnDeserializingCallBack(StreamingContext streamingContext)
{
this.Users = new List<MAASUsers>();
}
}
[DataContract(Name = "MAASUsers", Namespace = "http://schemas.datacontract.org/2004/07/myns")]
public class MAASUsers
{
[DataMember]
public string firstName { get; set; }
[DataMember]
public string lastName { get; set; }
[DataMember]
public string sourceEmail { get; set; }
[DataMember]
public int sourceAgentID { get; set; }
[DataMember]
public string targetEmail { get; set; }
[DataMember]
public int targetAgentID { get; set; }
}
Try to add Order and Name attribute to the Contract class.
Sample:
[DataMember(Order = 1, Name = "firstName")]
The data contract element name is "MAASUsers" but in the xml the element is named "MaasUsers". The data contract serializer is case sensitive so it will NOT match these two up.