How do you populate a list as a class object? For example, this does not work:
[DataContract]
public class JsonReviewFormFields
{
[DataMember]
public PersonalDevelopmentPlan personalDevelopmentPlan { get; set; }
}
public class PersonalDevelopmentPlan
{
public List<ShortTerm> shortTerm { get; set; }
public List<LongTerm> longTerm { get; set; }
}
public class ShortTerm
{
public string workRelated { get; set; }
public string structured { get; set; }
public string informal { get; set; }
public string reviewDate { get; set; }
}
public class LongTerm
{
public string workRelated { get; set; }
public string structured { get; set; }
public string informal { get; set; }
public string reviewDate { get; set; }
}
This is controller action:
public JsonReviewFormFields GetReviewForm()
{
PersonalDevelopmentPlan personalDevelopmentPlan = new PersonalDevelopmentPlan();
List<ShortTerm> _itemsShort = new List<ShortTerm>();
_itemsShort.Add(new ShortTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort;
List<LongTerm> _itemsLong = new List<LongTerm>();
_itemsLong.Add(new LongTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
jsonReviewFormFields.personalDevelopmentPlan.longTerm = _itemsLong;
return jsonReviewFormFields;
}
The code crashes at
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort;
It's probably a basic object orientated error. How do you populate the list?
You are not instantiating it, you have to instantiated the type first:
jsonReviewFormFields.personalDevelopmentPlan = new PersonalDevelopmentPlan();
and then set property of it:
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort
before that you also have to instantiate main class which i don't see in your controller action anywhere :
JsonReviewFormFields jsonReviewFormFields = new JsonReviewFormFields();
Related
there I have done this before but forgotten the syntax. I am making a JSON file which looks list the classes below but on the submit button I want to add them but I can't remember the syntax for when there is a list inside a list if that makes sense! my classes are:
public class LineItemCheck
{
public string Id { get; set; }
public string Check { get; set; }
public bool Yes { get; set; }
public bool No { get; set; }
}
public class LineItem
{
public string Category { get; set; }
public List<LineItemCheck> LineItemChecks { get; set; }
}
public class RootObject
{
public object SerialNumber { get; set; }
public object UnitNumber { get; set; }
public object Refrigerant { get; set; }
public object ModelNumber { get; set; }
public object BeltSize { get; set; }
public object FreezingUnitComments { get; set; }
public object VisualInspectionComments { get; set; }
public List<LineItem> LineItems { get; set; }
}
private void SubmitButton_Clicked(object sender, EventArgs e)
{
var checklist = new RootObject();
var checklistLineItem = new List<LineItem>();
var checklistLineItemChecks = new List<LineItemCheck>();
checklist.SerialNumber = SerialNumber.Text.ToString();
checklist.UnitNumber = UnitNumber.Text.ToString();
checklist.Refrigerant = Refrigerant.Text.ToString();
checklist.ModelNumber = ModelNumber.Text.ToString();
checklist.BeltSize = BeltSize.Text.ToString();
checklistLineItem.Add(new LineItem() {
Category = "Ziegra Machines Only",
LineItemChecks = new LineItemCheck(LineItemCheck.
),
});
as you can see the bottom section is wrong which is what i am trying to solve thanks
UPDATE: I remember the syntax myself sorry for posting but the answer i was looking for was:
var checklist = new RootObject();
var checklistLineItem = new List<LineItem>();
var checklistLineItemChecks = new List<LineItemCheck>();
checklist.SerialNumber = SerialNumber.Text.ToString();
checklist.UnitNumber = UnitNumber.Text.ToString();
checklist.Refrigerant = Refrigerant.Text.ToString();
checklist.ModelNumber = ModelNumber.Text.ToString();
checklist.BeltSize = BeltSize.Text.ToString();
checklistLineItem.Add(new LineItem() {
Category = "Ziegra Machines Only",
LineItemChecks = new List<LineItemCheck>()
{
new LineItemCheck()
{
Check = "",
},
new LineItemCheck()
{
Check = ""
}
}
});
If I understand your question correctly the following should be the right syntax:
checklistLineItem.Add(new LineItem()
{
Category = "Ziegra Machines Only",
LineItemChecks = new List<LineItemCheck>()
{
new LineItemCheck(),
new LineItemCheck(), ...
},
});
If I may: I would amend your models like so.
public class LineItem
{
public string Category { get; set; }
public List<LineItemCheck> LineItemChecks { get; private set; }
public LineItem()
{
LineItemChecks = new List<LineItemCheck>();
}
}
public class RootObject
{
public object SerialNumber { get; set; }
public object UnitNumber { get; set; }
public object Refrigerant { get; set; }
public object ModelNumber { get; set; }
public object BeltSize { get; set; }
public object FreezingUnitComments { get; set; }
public object VisualInspectionComments { get; set; }
public List<LineItem> LineItems { get; private set; }
public RootObject()
{
LineItems = new List<LineItem>();
}
}
That is, initializing all the collections in a constructor. Properties that expose collections and that can be null are ugly and, more importantly, unexpected. I never expect a collection to be null if it's exposed through a property, I expect it to just be empty, and that I can add stuff to it right away. I'm not in charge of a collection exposed by your object, it's your object's business to initialize itself properly.
This is the consensus in .NET land, you will be hard-pressed to find an example of a collection exposed by a library that is null upon instantiation of the object.
Also notice that I made the setters private, because no other object should be able to flat-out replace a collection exposed by a different object.
Then adding items to collections is simply a matter of:
var root = new RootObject();
var lineItem = new LineItem();
lineItem.LineItemChecks.Add(new LineItemCheck() { /* init properties here */ });
root.LineItems.Add(lineItem);
Below is my XML code.
<programs>
<program>
<ProgrameName>Test</ProgrameName>
<deviceTypes>
<DeviceType>POS</DeviceType>
<deviceTargets>
<DeviceNames>
<DeviceName>POS0001</DeviceName>
<DeviceName>POS0001</DeviceName>
<DeviceName>POS0001</DeviceName>
</DeviceNames>
<AttemptToIstall>True</AttemptToIstall>
<Mandetory>False</Mandetory>
<SkipIfOffline>False</SkipIfOffline>
</deviceTargets>
<AttemptToIstall>True</AttemptToIstall>
<Mandatory>False</Mandatory>
<SkipIfOffline>False</SkipIfOffline>
</deviceTypes>
</program>
please help me to write C# code using XmlSerializer.I want to create an object and serialize those object according to above XML.
below are my C# class.
public class ProgramP
{
public string ProgrameName { get; set; }
[XmlRoot("")]
public class DeviceTypes
{
public string DeviceType { get; set; }
[XmlRoot("")]
public class DeviceTargets
{
public string DeviceNames { get; set; }
public string AttemptToIstall { get; set; }
public string Mandetory { get; set; }
public string SkipIfOffline { get; set; }
}
[XmlElement("DeviceTargets")]
public DeviceTargets[] ArDeviceTargets { get; set; }
public string AttemptToIstall { get; set; }
public string Mandetory { get; set; }
public string SkipIfOffline { get; set; }
}
[XmlElement("DeviceTypes")]
public DeviceTypes[] ArDeviceType { get; set; }
}
Below is my C# code.can any body please correct me or suggest me where i have to add more class or how can i arrange my class so that i can get above XML as output.
public void ExportClass(string strFilePathExportedXML)
{
ProgramP ProgramP = new ProgramP
{
ProgrameName = "Test",
ArDeviceType = new ProgramP.DeviceTypes[] {
new ProgramP.DeviceTypes {
DeviceType = "POS1",
AttemptToIstall="True",
Mandetory="True",
SkipIfOffline="True",
ArDeviceTargets = new ProgramP.DeviceTypes.DeviceTargets[] {
new ProgramP.DeviceTypes.DeviceTargets {
DeviceNames="POS01",
AttemptToIstall="True",
Mandetory="True",
SkipIfOffline="True"
},
new ProgramP.DeviceTypes.DeviceTargets {
DeviceNames="POS02",
AttemptToIstall="True",
Mandetory="True",
SkipIfOffline="True"
}
}
};
TextWriter writer = new StreamWriter(strFilePathExportedXML);
XmlSerializer serializerOut = new XmlSerializer(typeof(ProgramP));
serializerOut.Serialize(writer, ProgramP);
writer.Close();
After mapping, you can use this:
public static YourClass LoadFromXMLString(string xmlText)
{
var stringReader = new System.IO.StringReader(xmlText);
var serializer = new XmlSerializer(typeof(YourClass ));
return serializer.Deserialize(stringReader) as YourClass ;
}
From this topic: Convert Xml to Object
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
my recent post one developer provide me solution. create class but how to assign values this class.. please help me
Create a class with required properties to be sent in request.
//for example
public class BookingInformation
{
public string booking_id { get; set; }
public ToLocation to_location { get; set; }
public string notes { get; set; }
}
public class ToLocation
{
public double latitude { get; set; }
public double longitude { get; set; }
public Address2 address { get; set; }
public object comment { get; set; }
public object airport { get; set; }
}
public class Address2
{
public string display_address { get; set; }
public string building_number { get; set; }
public string street_name { get; set; }
public string city { get; set; }
public string region { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
}
Assign the values to the object
Request request =new Request();
request.vehicles = new List<Vehicle>();
// and so on
//Use Newtonsoft.Json to serialize the object as:
var json = JsonConvert.SerializeObject(request);
//Invoke your request with json
using (var response = await httpClient.PostAsync("{supplier_id}/availability?version=2", json))
{
string responseData = await response.Content.ReadAsStringAsync();
}
but my method show error
public void ConvertJson()
{
BookingInformation objbooking = new BookingInformation();
objbooking.booking_id = "33";
objbooking.to_location.comment= "Saloon black";
objbooking.to_location.address.country= "UK";
var json = JsonConvert.SerializeObject(objbooking);
}
public void ConvertJson()
{
BookingInformation objbooking = new BookingInformation();
objbooking.booking_id = "33";
objbooking.to_location.comment= "Saloon black";
objbooking.to_location.address.country= "UK";
var json = JsonConvert.SerializeObject(objbooking);
}
You do not yet have a reference to an instance of ToLocation. Change to this:
public void ConvertJson()
{
BookingInformation objbooking = new BookingInformation();
objbooking.to_location = new ToLocation();
objbooking.to_location.address = new Address2();
objbooking.booking_id = "33";
objbooking.to_location.comment= "Saloon black";
objbooking.to_location.address.country= "UK";
var json = JsonConvert.SerializeObject(objbooking);
}
Based on your edits, you would also not yet have an instance of Address2, I updated the above to account for that as well.
Also read through the responses in: What is a NullReferenceException, and how do I fix it? for more information on how/why NullReferenceExceptions occur.
Another method of getting around this problem, so you don't have to remember to new up properties of the object that require it, is to do it from construction of the parent, like so:
public class BookingInformation
{
public string booking_id { get; set; }
public ToLocation to_location { get; set; }
public string notes { get; set; }
public BookingInformation()
{
to_location = new ToLocation();
}
}
public class ToLocation
{
public double latitude { get; set; }
public double longitude { get; set; }
public Address2 address { get; set; }
public object comment { get; set; }
public object airport { get; set; }
public ToLocation()
{
address = new Address2();
}
}
This will ensure when you create a new instance of BookingInformation the ToLocation and in turn Address2 have instances created at construction.
first create an instance of class ToLocation like this :
objbooking.to_location = new ToLocation();
I have this code:
public class TopTen
{
public int Id { get; set; }
public string ShortDesc { get; set; }
public string LongDesc { get; set; }
public Image Photo { get; set; }
}
public class Image
{
public string ImgUrl { get; set; }
public string AlterText { get; set; }
}
I can do like this to assign values:
new topten()
{
/*
here I can access and give values to my properties. BUT i cant
access and give values to the properties in my `Image` class.
This is a problem because I would like to upload the new object as a json-file.
So how do I access the properties in `Image`?
*/
}
var x = new TopTen
{
Id = 1,
Photo = new Image
{
ImgUrl = "pic.jpg",
AlterText = "This is a picture"
}
};
Hi I am new to entity framework. I have following objects
public partial class lr
{
public lr()
{
this.lr_history = new HashSet<lr_history>();
this.people = new HashSet<person>();
}
public int _id { get; set; }
public string name { get; set; }
public string notes { get; set; }
public virtual ICollection<lr_history> lr_history { get; set; }
public virtual ICollection<person> people { get; set; }
In my Web Api controller I have following code
public class lrController : ApiController
{
private CTM db = new CTM();
// GET api/addL
public IEnumerable<lr> Getlr()
{
from a in DbContext.Activities
return db.lr.AsEnumerable();
}
In above Get method it returns lr but i want to return my own object like
lr.id
lr.name
lr_history.description
lrh_history.rate
Can anyone show me how to achieve this? Than
Create a new model:
class HistoryModel
{
public int Id { get; set; }
public string Name { get; set; }
public string HistoryDescription { get; set; }
public string HistoryRate { get; set; }
}
and return that:
public IEnumerable<HistoryModel> Getlr()
{
from a in DbContext.Activities
return db.lr.AsEnumerable()
.Select(x => new HistoryModel
{
Id = x.id,
Name = x.name,
HistoryDescription = x.history.description,
HistoryRate = x.history.rate
});
}
Instade of return db.lr.AsEnumerable();
try this
return db.lr.ToList();