In C#, I'm building a class (simplified here for discussion purposes) that eventually will be serialized into some externally defined JSON:
{
"$schema": "http://example.com/person.json",
"name": "John",
"age": 86
}
In my code I would have something like:
public class Person
{
public const string $schema= #"http://example.com/person.json";
public string name {get;set; }
public int age {get; set;}
}
...
Person person = new Person();
person.name = "John";
person.age = 88;
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(person);
In my code above the $schema is causing an "Unexpected character '$' error. Is there a workaround?
Provide the attribute [DataContract] to your Person class.
Also, did you mean to make schema const?
[DataContract]
public class Person
{
[DataMember(Name = "$schema")]
public string schema { get; set; }
public string name { get; set; }
public int age {get; set;}
}
If using JSON.NET, you can use the JsonProperty attribute:
public class Person {
[JsonProperty(PropertyName = "$schema")]
public string schema {get; set;} = #"lsjdhflsjkdf";
public string name {get;set;}
}
Related
I am new to C# need help to convert json Object to Array
convert this json
[
{
"Id": 1000,
"Name": "May",
"Address": "odyssey",
"Country": "USA",
"Phone": "12345"
}
]
To
var details = {1000,May,odyssey,USA,12345};
Use Newtonsoft.Json to deserialize JSON to a specified .net type. You can deserialize to a class too, see below:
public class Person
{
public int Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
public string Country {get;set;}
public string Phone {get;set;}
}
var details = JsonConvert.DeserializeObject<Person>(json);
You are going to have to deserialize the Json String. Deserialize into array of objects.
JavaScriptSerializer js = new JavaScriptSerializer();
yourClass[] items = js.Deserialize<Yourclass[]>(yourJSONcontent);
Steps:
1. Create Model.
2. Get Data in string
3.Deserialize Object
And if you are confused How to create C# model from the json then use this link.
https://app.quicktype.io
Use This Model.
public class Test
{
[JsonProperty("Id")]
public long Id { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Address")]
public string Address { get; set; }
[JsonProperty("Country")]
public string Country { get; set; }
[JsonProperty("Phone")]
[JsonConverter(typeof(ParseStringConverter))]
public long Phone { get; set; }
}
string data="Your Json String"
var details = JsonConvert.DeserializeObject<Test>(data);
To make a list from your json values you can use a JObject, you don't have to know the objects stored in your Json in contrary to the others question.
JObject myObject = JsonConvert.DeserializeObject<JObject>(myJson);
List<object> myList = new List<object>();
foreach (var element in myObject)
{
myList.Add(element.Value);
}
If you already know what your json is made of, you can create a class that represent your object and implement the interface IEnumerable.
var myObject = JsonConvert.DeserializeObject<MyClass>(myJson);
var myArray = myObject2.ToArray():
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public int Phone { get; set; }
public object[] ToArray()
{
return new object[]
{
Id,
Name,
Address,
Country,
Phone
};
}
}
NB : the variable myJson in the previous codes is a string that represent your json as var myJson = "{\"Id\": 1000,\"Name\": \"May\",\"Address\": \"odyssey\",\"Country\": \"USA\",\"Phone\": \"12345\"}";
What I'am attempt to do is deserialize json and foreach through that object and get Name, Lastname, Id values from it.
I think deserializing works but how can I foreach throught thoes values of that object and write out?
ResponseFromServer =
responseFromServer"{\"ReportName\":\"TestReport\",\"Results\":[
{
\"Name\":\"Test1\",
\"Lastname\":\"Test2\",
\"ID\":\"1111111111\",
},{
\"Name\":\"Test\",
\"Lastname\":\"Test\",
\"Id\":\"222222222\"
}
]}" string
Code so far:
object jsonObj = new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(responseFromServer);
var myObject = jsonObj.GetType().GetProperties();
foreach (var obj in myObject)
{
Console.WriteLine(obj);
}
I recommend, that you create a class for your JSON, like this:
public class Result
{
public string Name { get; set; }
public string Lastname { get; set; }
public string Id { get; set; }
}
public class ResponseClass
{
public string ReportName { get; set; }
public List<Result> Results { get; set; }
}
And with this class, you can convert your object and get the properties in a foreach, like the Lastname.
var yourObjectWithStructure = JsonConvert.DeserializeObject<ResponseClass>(responseFromServer,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
foreach (var result in objec.Results)
{
var id = result.Id;
var lastName = result.Lastname;
var name = result.Name;
}
Update:
You have "ID" and "Id" in your JSON response. I suggest, that "ID" should be "Id". Is that right?
I would use newtonsoft and create a concrete object with a List Property
If you download the NewtonSoft framework:
Then you can create a class for your response...
public class Report
{
public string ReportName {get; set;};
public string TestReport {get; set;};
public List<Person> Results {get; set;}
}
public class Person
{
public string Name {get; set};
public string LastName {get; set};
public int ID {get; set;}
}
and you can deserialise directly into a list of that object class like this:
using System.Web.Script.Serialization;
===============
List<Person> persons = JavaScriptSerializer().Deserialize<List<Report>>(responseFromServer);
Foreach(Person p in persons)
{
//stuff
}
I am trying to convert a JSON object in to C# array.
this is the JSon I Getfrom the Server webrequest response:
string result = sr.ReadToEnd(); // this line get me response
result = {
"subjects": [{
"subject_id": 1,
"subject_name": "test 1",
"subject_class": 4,
"subject_year": "2015",
"subject_code": "t-1"
},{
"subject_id": 2,
"subject_name": "test 2",
"subject_class": 5,
"subject_year": "",
"subject_code": "t-2"
}]
};
dynamic item = JsonConvert.DeserializeObject<object>(result);
string iii = Convert.ToString(item["subjects"]);
I want to Get the Subjects and Save them in Array so i can use them for other purpose.
I use these to Method but always got the empty values.
List<subjects> subject1 = (List<subjects>)JsonConvert.DeserializeObject(iii, typeof(List<subjects>));
and
subjects[] subject2 = JsonConvert.DeserializeObject<subjects[]>(iii);
Please Help Me to Solve this.
And my Subject Class is..
class subjects
{
public int id { get; set; }
public string name { get; set; }
public int class_name { get; set; }
public string year { get; set; }
public string code { get; set; }
}
The property names won't match as is, because you subjects class don't have the 'subject_' prefix the JSON object has. Easiest fix is to change your property names as shown in Ali's answer. Just in case you need to keep your property names as is, you can also use a JsonProperty attribute to alter the serialization names (perhaps there's a more generic way using some sort of converter, but didn't think the amount of properties needed it)
class subjects
{
[JsonProperty("subject_id")]
public int id { get; set; }
[JsonProperty("subject_name")]
public string name { get; set; }
[JsonProperty("subject_class")]
public int class_name { get; set; }
[JsonProperty("subject_year")]
public string year { get; set; }
[JsonProperty("subject_code")]
public string code { get; set; }
}
If you never need the root subjects you can also skip it without dynamic or an extra class with something like:
subjects[] arr = JObject.Parse(result)["subjects"].ToObject<subjects[]>();
(JObject is part of the namespace Newtonsoft.Json.Linq )
You need to create a structure like this:
public class Subjects
{
public List<Subject> subjects {get;set;}
}
public class Subject
{
public string subject_id {get;set;}
public string subject_name {get;set;}
}
Then you should be able to do:
Subjects subjects = JsonConvert.DeserializeObject<Subject>(result);
I'm simply building a test Web API that takes a JSON payload and will simply send back the data in the array portion from my MVC Controller.
This is my current JSON string when serialized by my populated classes:
{"JobList":[{"ID":1,"Name":"Dave","Age":23,"StartDate":"10/23/2013 6:22:50 AM","JobTitle":"Developer"},{"ID":2,"Name":"John","Age":44,"StartDate":"10/23/2013 6:22:50 AM","JobTitle":"QA"},{"ID":3,"Name":"Dave","Age":23,"StartDate":"10/23/2013 6:22:50 AM","JobTitle":"Senior Developer"}]}
This is the object used to create this JSON:
var jobList = new JobsList()
{
JobList = new List<Jobs>()
{
new Jobs()
{
Age = 23,
ID = 1,
Name = "Dave",
StartDate = DateTime.Now.ToString(),
JobTitle = "Developer"
},
new Jobs()
{
Age = 44,
ID = 2,
Name = "John",
StartDate = DateTime.Now.ToString(),
JobTitle = "QA"
},
new Jobs()
{
Age = 23,
ID = 3,
Name = "Dave",
StartDate = DateTime.Now.ToString(),
JobTitle = "Senior Developer"
}
}
};
Here are my individual classes:
JobsList Class:
public class JobsList:IJobList
{
#region IJobList Members
public List<Jobs> JobList
{
get;
set;
}
#endregion
}
Jobs Class:
public class Jobs:Interfaces.IJobs
{
#region IJobs Members
public int ID
{
get;
set;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public string StartDate
{
get;
set;
}
public string JobTitle
{
get;
set;
}
#endregion
}
When I convert my JSON to produce classes through the use of JSON2Csharp the classes are produced as shown:
public class JobList
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string StartDate { get; set; }
public string JobTitle { get; set; }
}
public class RootObject
{
public List<JobList> JobList { get; set; }
}
This to me seems incorrect. Can anyone explain why I am not getting a 'Jobs' node in my JSON set to the JobsList array? And why do the generated JSON2CSharp classes map my 'Jobs' class as a JobList class?
Basically, it's because deserializer (in this case, JSON2CSharp) doesn't know what you named your original classes. Or how you structured them, for that matter. It doesn't know about any of that stuff you posted below "my current JSON string."
When you hand it that JSON object, that's all the information it is working with. So, it can tell that there's some sort of object (which it calls "RootObject"), which has an array of objects called "JobList". So it called the class "JobList". It had a choice there -- it could have simply called the list "JobList" and named the object something else... but it has no way of knowing that it was originally from an object named "Jobs", because that's not in the JSON. A different deserializer may have done it differently.
I am not familiar with JSON2CSharp specifically, so I don't know if it can do this, but there are frameworks that, given the object definition, can parse a JSON string with consistently named fields and load it into that object. For example, with Json.NET, you can do something like this:
JobsList jobList = JsonConvert.DeserializeObject<JobsList>(JsonString);
What I'm trying to do is serialize Nested classes. My code first:
[Serializable]
public class SampleClass
{
[Serializable]
public class Person
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Age")]
public ushort Age { get; set; }
}
[Serializable]
public class Adress
{
[XmlElement("Street")]
public string Street { get; set; }
[XmlElement("House number")]
public int Number { get; set; }
}
public SampleClass()
{
}
public SampleClass(string _name, byte _age, string _street, int _number)
{
Person p = new Person();
p.Name = _name;
p.Age = _age;
Adress a = new Adress();
a.Street = _street;
a.Number = _number;
}
}
I want to get xml like this
<?xml version="1.0"?>
<SampleClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<Person>
<Name></Name>
<Age></Age>
</Person>
<Adress>
<Street></Street>
<HouseNumber></HouseNumber>
</Adress>
</SampleClass>
When I serialize this SimleClass:
using (Stream str = new FileStream(#"C:/test.xml", FileMode.Create))
{
XmlSerializer serial = new XmlSerializer(typeof(SampleClass));
SampleClass sClass = new SampleClass("John",15,"Street",34);
serial.Serialize(str, sClass);
label1.ForeColor = Color.Black;
label1.Text = "Ok";
}
It's give me test.xml file but inside of that file is :
<?xml version="1.0"?>
<SampleClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
What am I doing wrong?
Thanks for advance:)
What you really want serialize is this :
Person p = new Person();
p.Name = _name;
p.Age = _age;
Adress a = new Adress();
But these variables are local.
Create a property of each one and decorate them with the serializable attribute too. Now it will work.
public SampleClass(string _name, byte _age, string _street, int _number)
{
this.Person = new Person();
Person p = this.Person;
p.Name = _name;
p.Age = _age;
this.Adress = new Adress();
Adress a = this.Adress;
a.Street = _street;
a.Number = _number;
}
[Serializable]
public Person Person { get; set; }
[Serializable]
public Adress Adress { get; set; }
BTW: Address takes 2 d.
If you serialize an instance of the main class, the serializer will serialize an instance of the nested class if and only if the object graph contains one. In this respect, nested classes are exactly the same as all other classes.
Basically you have to create properties for the nested class in the main one
This line is invalid:
[XmlElement("House number")]
As an element name can't have a space in it.
The reason you are getting an empty XML file is that your SampleClass has no properties to serialize.
In the constructor you are creating a Person and Address which are thrown away as soon as the method exists as you are not using them for anything. Change your code as follows and you should have more success.
[Serializable]
public class SampleClass
{
[Serializable]
public class Person
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Age")]
public ushort Age { get; set; }
}
[Serializable]
public class Adress
{
[XmlElement("Street")]
public string Street { get; set; }
[XmlElement("HouseNumber")]
public int Number { get; set; }
}
public SampleClass()
{
}
public SampleClass(string name, byte age, string street, int number)
{
this.Person = new Person
{
Age = age,
Name = name
};
this.Adress = new Adress
{
Street = street,
Number = number
}
}
public Person Person { get; set; }
public Address Address { get; set; }
}