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 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 2 years ago.
Improve this question
I am currently learning C# and how to use API's. One of the API's i need to use comes from TVmaze. However I am having a hard time figuring out how to use the JSON data I've been given with this example API call: http://api.tvmaze.com/search/shows?q=girls
Basically what I am trying to do is grab the Show Name, Days that it Airs and Time of day it Airs and store them within strings or a List (more or less for storing the data about what days it airs in cause multiple)
Any help is appreciated, and I do apologize in advance if this question is super vague and that I don't have anything to show or work off of at the moment.
Edit: Did I quick right up on where I am up to.
namespace MajorProjectTvApplication
{
public class LoadTVShows
{
public string name;
public string summary;
public string time;
public string days;
public async Task<bool> GetAPI(string worldLocation)
{
using (var client = new HttpClient())
{
var response = await client.GetAsync("");
var responseString = await response.Content.ReadAsStringAsync();
var rawTvListings = JsonConvert.DeserializeObject<OpenTVGuideResponse>(responseString);
}
}
}
}
What you could do is to create POCO objects that contain properties that you care about. For example something like this:
public class Details
{
public Show show { get; set; }
}
public class Show
{
public string name { get; set; }
public Schedule schedule { get; set; }
public string summary { get; set; }
}
public class Schedule
{
public string time { get; set; }
public List<string> days { get; set;}
}
It is important that the names of properties are exactly the same like those in the JSON file. The structure of your objects also metters. Should be like in the JSON file. Otherwise it'll fail to deserialize. If you really want to have different name you need to use data annotation such as this one.
[JsonPropertyName("name")]
public string DifferentNameStillWorks { get; set; }
Then you can deserialize your JSON to these objects. The JsonSerializer will ignore all the data that you're not interested in. As a result you'll get the list of Details.
static async System.Threading.Tasks.Task Main(string[] args)
{
HttpClient client = new HttpClient();
var result = await client.GetAsync("http://api.tvmaze.com/search/shows?q=girls").Result.Content.ReadAsStringAsync();
var listOfDetails = JsonSerializer.Deserialize<List<Details>>(result);
}
Don't forget using System.Text.Json; at the beginning.
PS Check out why you should not put HttpClient into using statement. Eg. here: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
I would normally use the approach given by #LilacBlue in their answer but since the json contains a lot of properties and you're only interested in a few of them, you might not want to define the whole model.
An alternative approach would be to install the NuGet package Newtonsoft.Json and try something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace ConsoleApp
{
class Program
{
static async Task Main(string[] args)
{
var client = new HttpClient() { BaseAddress = new Uri("http://api.tvmaze.com/") };
var response = await client.GetAsync("search/shows?q=girls");
var json = await response.Content.ReadAsStringAsync();
var shows = JArray.Parse(json);
var times = shows.Children()
.Select(c => c["show"])
.Select(show => new Show()
{
Name = show["name"].ToString(),
Time = show["schedule"]["time"].ToString(),
Days = show["schedule"]["days"].Children().Select(c => c.ToString()).ToList()
})
.ToList();
}
}
public class Show
{
public string Name { get; set; }
public string Time { get; set; }
public IEnumerable<string> Days { get; set; }
}
}
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);
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
Is there a way to get the specific items from the list of a model without using a foreach of the list? like if you return a List<model> holding a model with a few differnt items to specifically call those item.
If you want a list of a specific item that's within your list then you can use LINQ to return those items, for example:
var customerNames = customersList.Select(customer => customer.Name);
This would give you a string collection with all of your customer names equal to the amount that was in your original list.
Or if you would like to retrieve a number of different items from your model list then you may want to look into creating a class specifically for stripping out those items, for example:
public class CustomerContactDetails
{
public string Address { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
}
...
var contactDetails = customersList.Select(customer => new CustomerContactDetails { Address = customer.Address, Email = customer.Email, Telephone = customer.Telephone });
You can use C# LambdaExpression, like this:
var yourModel = modelList.Where(x => x.Id = 12).Select(x).First();