Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
i have some strings from database
email1 link1 data1
email1 link1 data2
email1 link2 data3
email2 link3 data4
How can i get such а json?
{log:[
{email: email1, link:link1, data:[data1,data2]},
{email: email1, link:link2, data:[data3]},
{email: email2, link:link3, data:[data4]}
]}
I do not know how to create a date array for given fields
You may try to first load your data in an object tree and then use a json converter like Json.Net. But you need to have a consistent format for your data. A kind of thing like the code below :
class Data{
//to be more defined maybe a string could be a start
string value;
}
class Log{
string email;
string link;
List<Data> data;
}
List<Log> myLog = new List<Log>();
// load your "log" data into this list
string json = JsonConvert.SerializeObject(myLog);
A slightly different answer from the first answer.
Let's assume you already able to get the records from the database into this class.
public class Log
{
public string Email { get; set; }
public string Link { get; set; }
public string Data { get; set; }
}
You can then group the logs by email and link using the following LINQ syntax.
var logs = new List<Log>(); // The list should come from the records in the database.
var result = new
{
Log = logs.GroupBy(x => new { x.Email, x.Link })
.Select(y => new { y.Key.Email, y.Key.Link, Data = y.Select(z => z.Data) })
};
And use Newtonsoft.Json to serialize it.
var json = JsonConvert.SerializeObject(result);
Related
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\"
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I wanted to select data within the dates given using linq query (.net core).
The entity is
public List<Slots> Dates { get; set; }
and
public class Slots
{
public string SlotName { get; set; }
public DateTime SlotDate { get; set; }
}
This is the scenario. I want to select all data within dates from Dates but I need to match the date with SlotDate.
I tried
IEnumerable<Programs> programs = await _programRepository.GetAllAsync(p => p.Dates.Select(d => d.SlotDate >= startDate && d.SlotDate<=endDate));
Linq will handle the DateTimes just fine, you can use standard greater-than/less-than operators. Very basic example:
using System;
using System.Collections.Generic;
using System.Linq;
public class Slots
{
public string SlotName { get; set; }
public DateTime SlotDate { get; set; }
}
public class Program
{
public static void Main()
{
List<Slots> Dates = new List<Slots>();
Dates.Add(new Slots()
{
SlotName = "Test1",
SlotDate = DateTime.Now
});
Dates.Add(new Slots()
{
SlotName = "Test2",
SlotDate = DateTime.Now.AddSeconds(5)
});
var selection = Dates.Where(s => s.SlotDate > DateTime.Now).Single();
Console.WriteLine(selection.SlotName);
}
}
Try it out here. Obviously you won't be using DateTime.Now, but the simple 'Where' line is all you'll need. If you want to find values between two dates, just add an && and another condition.
This is just getting a .Single() value from the selection. If you want to find multiple values, use .ToList() - the value you get back will be a list that you can handle like any other list.
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.
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.
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);