'What code will insert a string into a List that is in a class in C# [duplicate]
I am not experienced in C# I am trying to serialize some classes into a json string Here is an example of the json string I am trying to output and you can see the description is an array of lines
{
"activities": [
{
"userName": "Gavin",
"activity": {
"id": "action001",
"description": ["this is a long description"]
}
}
]
}
Here are the classes I have setup to model the json:
public class RootObject
{
[JsonProperty("activities")]
public List<Activities> activities { get; set; }
}
public class Activities
{
[JsonProperty("userName")]
public string UserName { get; set; }
[JsonProperty("activity")]
public _activity activity { get; set; }
}
public class _activity
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("description")]
public List<string> Description { get; set; }
}
Here is the C# code to create the example json:
var model = new RootObject();
model.activities = new List<Activities>
{
new Activities
{
UserName = "Gavin"
activity = new _activity
{
id = "action001",
Description[0] = "long description"
},
}
The problem is that when I code Description[0] = "long description" I get an error in Visual Studio saying "Invalid initializer member declarator"
I would appreciate it if someone could show me the C# code I need in order to populate the Description list. Thank you
Solution 1:[1]
Create a string list as:
Description = new List<string> { "long description" }
var model = new RootObject();
model.activities = new List<Activities>
{
new Activities
{
UserName = "Gavin"
activity = new _activity
{
id = "action001",
Description = new List<string> { "long description" }
},
}
};
Solution 2:[2]
The correct code is as follows:
public class RootObject
{
[JsonProperty("activities")]
public List<Activities> Activities { get; set; } = new List<Activities>();
}
public class Activities
{
[JsonProperty("userName")]
public string UserName { get; set; }
[JsonProperty("activity")]
public Activity Activity { get; set; } = new Activity();
}
public class Activity
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("description")]
public List<string> Description { get; set; } = new List<string>();
}
var activity = new Activity
{
Id = "action001"
};
activity.Description.Add("long description");
var model = new RootObject()
{
Activities = new List<Activities>()
{
new Activities()
{
UserName ="Gavin",
Activity = activity
}
}
};
Reference
https://docs.microsoft.com/dotnet/csharp/fundamentals/coding-style/coding-conventions
*
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yong Shun |
| Solution 2 | Choi Min Gyu |
