C# parse string into object [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
For the following text:
Item 1:
student-pay
history 320.00
math 500.10 extra
Item 2:
history 220.00
math 200.10
I would like to parse this text into an Item class. Is there a more efficient way to do this?
I have the following:
var result = input.Split(
new[] { "item", "Item" },
StringSplitOptions.RemoveEmptyEntries);
foreach (string item in result)
{
var lineItems = item.Split(
new[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries);
foreach (var lineItem in lineItems.Skip(1)) // remove ":"
{
// split line again
// check if numeric
}
}
public class Course
{
public bool StudentPay { get; set; }
public ICollection<CourseItem> JobItems { get; set; }
}
public class CourseItem
{
public string Name { get; set; }
public decimal Cost { get; set; }
public bool Extra { get; set; }
}
I want to end up with List<Items>

Given that data format your stuck with having to hand code a one off solution.
A much better approach is to use a json format. Get Newtonsoft.json. It's a one liner to serialize it and a one liner to deserializer. Add another line for File.Write and File.Read and away you go.
Use JsonConvert.Serialize and JsonConvert.Deserialize, will work most classes (unlike xmlserializer).

Json is probably a better solution but it require having the control of the input string being formatted to json format.
If you have to use your existing string as input, I suggest you to use RegEx to parse each line for the object creation. Regex is the old-fashion way to tackle your problem.

Related

How to read parse JSON String in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to read a JSON string in C# (in fact, it is much longer, but just to show the structure...) This is the string that I receive.
42["cti-agentes","{
\"6139\":{
\"id_agents_interface\":\"453\",
\"agent\":\"6139\",
\"interface\":\"contact1\",
\"logintime\":\"2019-11-26 15:08:46\",
\"pausetime\":\"2019-12-31 13:28:36\",
\"paused\":\"si\",
\"id_pausa\":null,
\"invalid\":\"no\",
\"invalidtime\":null,
\"fullcontact\":\"contact1\",
\"textoterminal\":\"contact1\"
},
\"6197\":{
\"id_agents_interface\":\"5743\",
\"agent\":\"6197\",
\"interface\":\"contact1\",
\"logintime\":\"2020-01-16 10:16:17\",
\"pausetime\":null,
\"paused\":\"no\",
\"id_pausa\":null,
\"invalid\":\"no\",
\"invalidtime\":null,
\"fullcontact\":\"contact2\",
\"textoterminal\":\"contact2\"
}
}"]
The String is supposed to be an array of 'agents'. 6139 is one agent, with all its properties, and 6197 is another agent. In this example there are only two agents, but in the real string there are many of them.
I am not very familiar with the JSON format, but I tried to validate it in this web https://jsonformatter.curiousconcept.com/ and I can't make it work, so maybe I have to "clean" the string a little bit before parsing it? Hope you can help.
The aplication should be able to read the JSON string and parse it to a .NET object, I tried the JsonConvert.DeserializeObject() and JArray.Parse() functions but neither of them have worked for me.
Any help?
The first part seems to be an int, you have multiple way to remove it:
var withoutNumberPrefix = new string(input.SkipWhile(c=> Char.IsDigit(c)).ToArray());
var fixedSize = input.Substring(2, input.Length - 2);
var always42 = input.TrimStart(new[] { '4', '2' });
Once you have done that you have a List<string>, where the first value is the type and the second the "array" of that type.
var listResults = JsonConvert.DeserializeObject<string[]>(fixedSize);
You can deserialize the second part:
var result = JsonConvert.DeserializeObject<Dictionary<int,CtiAgentes>>(listResults[1]);
Into the matching type, created with a simple copy past using those tool
How to auto-generate a C# class file from a JSON string
:
public partial class CtiAgentes
{
[JsonProperty("id_agents_interface")]
public int IdAgentsInterface { get; set; }
[JsonProperty("agent")]
public int Agent { get; set; }
[JsonProperty("interface")]
public string Interface { get; set; }
[JsonProperty("logintime")]
public DateTimeOffset Logintime { get; set; }
[JsonProperty("pausetime")]
public DateTimeOffset? Pausetime { get; set; }
[JsonProperty("paused")]
public string Paused { get; set; }
[JsonProperty("id_pausa")]
public object IdPausa { get; set; }
[JsonProperty("invalid")]
public string Invalid { get; set; }
[JsonProperty("invalidtime")]
public object Invalidtime { get; set; }
[JsonProperty("fullcontact")]
public string Fullcontact { get; set; }
[JsonProperty("textoterminal")]
public string Textoterminal { get; set; }
}
In this Live demo, you will notice that there is no string manipulation except "remove the 42". Not backslash not quote were modify. It's a json hardcoded in a string Store Hardcoded JSON string to variable
Nota bene:
I used DateTimeOffset for Pausetime and Logintime, because there where no timezone in that input. You can use Datetime but it will be nice to know if it's gmt or localized data.
For all the null value I choosed object. because I don't know the type. And that will go boom sooner or later with data. One can assume that id is a int and invalid time a DateTimeOffSet, but I can't make that decision.
There are multiple issues with your text. I will try to elabroate on them in the following parts...
42 prepended to the string
Quite obvious to all of us - this just should not be there
Your json object is a list
Since your json object starts with [ it's actually a string list, that has to be separated by ,, e.g. ["a", "b", "c"], which is probably the reason for the next point...
Your json value objects are strings
First of all the following is kind of a mixture of a string list and a json object
"cti-agentes","{
\"6139\":{
\"id_agents_interface\":\"453\",
\"agent\":\"6139\",
\"interface\":\"contact1\",
\"logintime\":\"2019-11-26 15:08:46\",
\"pausetime\":\"2019-12-31 13:28:36\",
\"paused\":\"si\",
\"id_pausa\":null,
\"invalid\":\"no\",
\"invalidtime\":null,
\"fullcontact\":\"contact1\",
\"textoterminal\":\"contact1\"
},
But also if you wanted to have json objects, you may not have surrounding "'s around your objects.
symbol because it makes it a string instead of a json object, e.g.
"employee_1": { "name": "dominik" } instead of
"employee_1": "{ "name": "dominik" }" like it is in your example.
Conclusion
The system providing you a "json" does not provide a json and instead some string that is kind of similar to a json. Why? I don't know - probably "42" lol :)
The best advice is probably to talk to the guy who made the api and fix it
What can I do now?
Maybe you can try to extract the value for cti-agentes, since the following is actually a valid json you should be able to parse.
{
\"6139\":{
\"id_agents_interface\":\"453\",
\"agent\":\"6139\",
\"interface\":\"contact1\",
\"logintime\":\"2019-11-26 15:08:46\",
\"pausetime\":\"2019-12-31 13:28:36\",
\"paused\":\"si\",
\"id_pausa\":null,
\"invalid\":\"no\",
\"invalidtime\":null,
\"fullcontact\":\"contact1\",
\"textoterminal\":\"contact1\"
},
\"6197\":{
\"id_agents_interface\":\"5743\",
\"agent\":\"6197\",
\"interface\":\"contact1\",
\"logintime\":\"2020-01-16 10:16:17\",
\"pausetime\":null,
\"paused\":\"no\",
\"id_pausa\":null,
\"invalid\":\"no\",
\"invalidtime\":null,
\"fullcontact\":\"contact2\",
\"textoterminal\":\"contact2\"
}
}

How to Split string into an array using C#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
When Domain Model property Name gets data from the database it's a string "David,James", but I have created another View Model to convert that string into an array ["David","James"]. I have used my ViewModel in the read method now, now the ViewModel should read the Name property as ["David","James"]. I am not sure how to make it happen.
I would appreciate if anybody has any suggestion on how to make it happen.
Domain Model:
public class FullName
{
public Int32 Id { get; set; }
public String Name { get; set; }
public String Address {get; set;}
}
View Model:
public class NameViewModel
{
public Int32 Id { get; set; }
public List<string> Name { get; set; }
public String Address { get; set;}
}
Read Method:
public ActionResult Name_Read([DataSourceRequest]DataSourceRequest request)
{
try
{
DataSourceResult result = Identity.ToDataSourceResult(request, NameViewModel => new
{
Id = NameViewModel.Id,
Name = NameViewModel.Name ,
Address = NameViewModel.Address,
});
return Json(result);
}
I think you're looking for something like this:
DataSourceResult result = Identity.ToDataSourceResult(request, dataModel => new NameViewModel
{
Id = dataModel.Id,
Name = dataModel.Name.Split(","),
Address = dataModel.Address,
});
// typical delimiter characters
char[] delimiterChars = { ' ' };
// verify the name exists
if (!String.IsNullOrEmpty(name))
{
// Get the list of strings
string[] strings = name.Split(delimiterChars);
if (strings != null)
{
if (strings.Length == 1)
{
firstName = strings[0];
}
else if (strings.Length == 2)
{
firstName = strings[0];
lastName = strings[1];
}
else if (strings.Length == 3)
{
firstName = strings[0];
middleName = strings[1];
lastName = strings[2];
}
}
}
I am not at Visual Studio, but I think that is right.
When Domain Model property Name gets data from the database it's a string "David,James"
That is a terrible mistake in database Design. The ideal solution would be to fix the Backend Database to actually have two fields for those distinct values.
Failing that, the next step would be to try and split on the DB side. Many modern DBMS support Views, wich can have columns computed from actuall rows. That way you could avoid issues, like different code splitting the same input differently. And you could even henceforth treat it like it was always two Columns.
If you really want or need to it in code and given this exact input format, String.Split() can deal with this. Of coruse you can get fancier, and use stuff like Regular Expressions instead. But for this example, Split seems perfectly suiteable for the case.

How do I sort a text file into different lists? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
NS01 EW24
$1.04
$1.32
20
NS04 EW21
$1.02
$1.62
9
where NSxx and EWxx is always 4 characters,
the money is always 3 digit with a dollar sign, and
the last number can be 1 or 2 digits.
Question: How do I sort NSxx into 1 list, EWxx into another list, first money into another list, second money into another list, and the last number into another list?
(in the text file, which is realy long, there are also other NSxx and EWxx which are CCxx, CGxx, DTxx, NExx)
using (StreamReader fare = new StreamReader("fare.txt"))
{
string line;
while ((line = fare.ReadLine()) != null)
{
}
}
I would not use different lists but instead create a class able to store one data record.
public class Data
{
public string Code1 { get; set; }
public string Code2 { get; set; }
public decimal Price1 { get; set; }
public decimal Price2 { get; set; }
public int Number { get; set; }
}
But use better names. (I don't know what kind of data this is.)
And assuming that the file always contains chunks of 4 lines representing one data record
var fare = File.ReadLines("fare.txt").GetEnumerator();
var list = new List<Data>();
while (fare.MoveNext()) {
if (!String.IsNullOrEmpty(fare.Current)) { // Not an empty line at the end of the file.
var data = new Data();
data.Code1 = fare.Current.Substring(1, 3);
data.Code2 = fare.Current.Substring(5, 3);
fare.MoveNext();
data.Price1 = Decimal.Parse(fare.Current.Substring(1)); // Skip the $ sign.
fare.MoveNext();
data.Price2 = Decimal.Parse(fare.Current.Substring(1));
fare.MoveNext();
data.Number = Int32.Parse(fare.Current);
list.Add(data);
}
}

List that contains list that contains list and so on in c# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
This is code:
public class Comment
{
public DateTime CreateAt { get; set; }
public Comment ParentComment { get; set;}
public List<Comment> SubComments { get; set; }
public string Text { get; set; }
}
I'am trying to do something like on facebook. You can comment every single comment, so there will be like a tree of comments.. I'am having trouble with trying to display all the comments, precisely text. I can't figure out how to do that. If anyone could help I'll appreciate it!
You can use recursion for process each comment and their sub comments for example:
public void checkComment(Comment comment)
{
//Check if the comment is valid
if (comment != null)
{
//Do whatever you want to do with your comment for example print to console
Console.WriteLine(String.Format("Comment: {0}", comment.Text));
//Check if i have any sub comments
if (comment.SubComments.Count > 0)
{
//Process each sub comment (recursive)
comment.SubComments.ForEach(x => checkComment(x));
}
}
}

how to split single data from string..? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to get single data from a string can any one help me to split the ID content alone. My Code that stores the Result value:
private void sendPostCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
MessageBox.Show("Success..");
MessageBox.Show(e.Result);
string res=(string)e.Result;//here res contains my data..
//need to get ID value alone.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Use json2csharp to create a C# class for your JSON-string. Simplified example from your JSON:
public class RootObject
{
public string name { get; set; }
public string description { get; set; }
public string timezone { get; set; }
public string id { get; set; }
}
//You can make the id of type int if you want
Fastest way for working with JSON is using Json.NET. Download the zip and use the dll from folder Portable40, this is the version that is compatible with Windows Phone 7. Reference the dll in your project and then your code should look similar to this:
string jsonString = "{\"name\":\"Qwer\", \"description\":\"\", \"timezone\":\"UTC\", \"id\":\"2912\"}";
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonString);
int id = Convert.ToInt32(obj.id);
//value of id: 2912
If you don't want a class to deserialize into you could do something like this:
JsonObject jsonObject = new JsonObject(e.Result);
string res= jsonObject["id"];
I solved my problem guys.. here is my sample code.. it works wel..
dynamic stuff = JsonConvert.DeserializeObject(res);
int id=stuff.id;
You should probably deserialize this into an object and then retrieve your values.
First create a class, with all your fields as parameters.
class ResponseObject{
public string Name{get;set;}
public string Description{get;set;}
...
}
and so on.
Then you can deserialize this response,
ResponseObject response = new JavaScriptSerializer().Deserialize<ResponseObject>(res);

Categories

Resources