How to convert List<ClassModel> to List<string> easily - c#

I have an ASP.NET Core 3.1 WebAPI which contains a class model called ImagePath that has one property only called filename, my problem is how can I convert or map a list of this class to list of string.. I mean it takes the property filename and add it to a list of string BUT without using any kind of loops (for, foreach, while..)
The data that comes from the API
"images": [
{
"filename": "6f2290d2-c26f-4132-b7dc-c70ca3bbadb5.jpg"
},
{
"filename": "8057c245-d980-40b5-964e-5fda69684300.jpg"
},
{
"filename": "a085f172-e711-4520-abab-1defc8e9dde8.jpg"
},
{
"filename": "db5c2296-0679-4e02-9e34-674aaa578be8.jpg"
}
],
what I want is this
"images": [
"6f2290d2-c26f-4132-b7dc-c70ca3bbadb5.jpg",
"8057c245-d980-40b5-964e-5fda69684300.jpg",
"a085f172-e711-4520-abab-1defc8e9dde8.jpg",
"db5c2296-0679-4e02-9e34-674aaa578be8.jpg"
],
Any solutions?

listClassModel.Select(p => p.filename).ToList()

Related

Pact Net, Two different body structure comparison in Contract Test Is possible using pact?

I have a question in Pact. I have two body structure, how to compare this using pact dotnet? I see .PactVerify("url") simply compare the entire body of contract json file and it fails.
consumer
{
"name":"xxx1",
"isemployed":"yes",
"country":"USA"
}
provider:
[
{
"type": "work",
"employee": [
{
"name": "xxx1",
"isemployed": "yes",
"country": "USA"
},
{
"name": "xxx2",
"isemployed": "yes",
"country": "india"
}
]
}
]

JSON extract date from matching string

I am entirely new to JSON, and haven't got any familiarity with it at all. I'm tinkering around with some JSON data extracts to get a feel for it.
Currently, I have a chat export which has a large number of keys. Within these keys are a "date" key, and a "from_id" key.
I would like to search a JSON file for a matching value on the "from_id" key, and return all the values against the "date" keys with a matching "from_id" value.
For example:
{
"name": "FooBar Chat Group",
"type": "textchat",
"id": 123456789,
"messages": [
{
{
"id": 252930,
"type": "message",
"date": "2021-03-03T01:39:30",
"date_unixtime": "1614735570",
"from": "Person1",
"from_id": "user1234",
"text": "This is a message!"
},
{
"id": 252931,
"type": "message",
"date": "2021-03-03T01:41:03",
"date_unixtime": "1614735663",
"from": "Person2",
"from_id": "user9876",
"text": "This is a reply!"
},
{
"id": 252932,
"type": "message",
"date": "2021-03-03T01:42:01",
"date_unixtime": "1614735721",
"from": "Person2",
"from_id": "user9876",
"text": "This is some other text!"
},
{
"id": 252933,
"type": "message",
"date": "2021-03-03T01:42:44",
"date_unixtime": "1614735764",
"from": "Person1",
"from_id": "user1234",
"text": "Yeah, indeed it is!"
}
]
}
I want to search from_id "user1234", and for it to return the following:
2021-03-03T01:39:30
2021-03-03T01:42:44
These are the two dates that have a matching from_id.
How would I go about doing something like this, please?
I am entirely new to this, so a super basic explanation with resources would really be appreciated. Thanks!
you can try this c# code. At first you have to parse your json strig to create an object from string. Then you can use LINQ to get the data you need
using Newtonsoft.Json;
JArray messages = (JArray) JObject.Parse(json)["messages"];
string from_id="user1234";
DateTime[] dates = messages
.Where(m=> (string) m["from_id"] ==from_id)
.Select(m => (DateTime) m["date"])
.ToArray();
Assuming your sample is part of a JSON Array - starts with [ and ends with ] - you should be able to iterate and conditionally select what you want.
In javascript, you can use a for of to iterate through and an if to match your request:
for(let item of array){
if(item['from_id'] == 'user1234')
console.log(item.date);
}
As we don't know the language you're actually using, a more wide code version of it could be something like:
for(let i=0;i < array.length; i++){
if(array[i]['from_id'] == 'user1234'){
print(array[i]['date']);
}
}

.net Core & Swashbuckle/Swagger: How to provide raw json example?

I have a WebAPI controller with an operation returning a JSON schema. This JSON return value cannot be created by serializiation, so I designed the operation method as follow:
[HttpGet("{serviceName}/contract")]
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(object))]
public IActionResult GetContract(string serviceName)
{
return Content("{ \"type\": \"object\" }", "application/json"); // for example ...
}
Now I like to have a or some documented return values for Swagger. But I'm unable to do that. There is the SwaggerRequestExample attribute, but as said before, this requires a return type which in my case is not applicable.
Basically I search for a way of something like that (just dynamic):
[SwaggerResponseExample((int)HttpStatusCode.OK, "{\"anyJson\": \"Yes, I am!\"}")]
Or of course, even better like that:
[SwaggerResponseExample((int)HttpStatusCode.OK, RawJsonFabricType="TypeName", RawJsonStaticMethod="MethodName")]
Use case: The JSON schemas I need to return in operation method are stored in a database and are not created within the program code itself.
A concrete example of such a JSON schema value is:
{
"$id": "https://example.com/person.schema.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"lastName": {
"type": "string",
"description": "The person's last name."
},
"age": {
"description": "Age in years which must be equal to or greater than zero.",
"type": "integer",
"minimum": 0
}
}
}
Help will be very appreciated.
Thanks!
I'm using c#.net core 6.
Afer trying arround I came to the solution:
First: Add ExampleProvider and use generic type JsonDocument (from System.Text.Json):
public class ServiceDemandContractExampleProvider : IExamplesProvider<JsonDocument>
{
/// <inheritdoc/>
public JsonDocument GetExamples()
{
var jsonToShow = JsonDocument.Parse(#"{
""$id"": ""https://example.com/person.schema.json"",
""$schema"": ""https://json-schema.org/draft/2020-12/schema"",
""title"": ""Person"",
""type"": ""object"",
""properties"": {
""firstName"": {
""type"": ""string"",
""description"": ""The person's first name.""
},
""lastName"": {
""type"": ""string"",
""description"": ""The person's last name.""
},
""age"": {
""description"": ""Age in years which must be equal to or greater than zero."",
""type"": ""integer"",
""minimum"": 0
}
}
}");
return jsonToShow;
}
}
To JsonDocument.Parse put whatever JSON (in my case loaded content from database).
Then add the follow attributes to the operation method:
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(object))]
[SwaggerResponseExample((int)HttpStatusCode.OK, typeof(ServiceDemandContractExampleProvider))]
And it works:

Deserializing random json file in c#

i am trying to take in a json file and iterate over some of the values.
The file is 73000 lines long, and i only need a few values.
Here is an example of the json file:
{
"value" : "key"
"value" : "key"
"Owner": {
"UserId": xxx,
"Username": "xxx",
},
"Items": [
{
"value": "key",
"value": "key",
"Comment": "",
"value": {
"value": {
"value": "key",
"value": "key",
"value": "key",
}
},
"CustomFields": [
{
"Name": "something",
"Content": "true"
}
]
}
]
}
How do i load this in without defining the object? i need 5 values per item, from different nesting levels, though i dont want to define the class as the file is more than 70.000 lines.
I tried doing it like this:
var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
But that way i will get an error when i try to itterate over items, as items value will now be a string!
foreach (Dictionary<string, string> result in values["items"])
Is there a way to load the file, defining the class based on the json schema?
I need values from different levels in the file, some at root level some nested.

Parsing JSON in C#

I have a JSON string that I am sending to a c# server. It comprises an array of Event objects and an Array of relationship objects. The relationship objects describe the database table relationships.
However I'm having trouble getting data from the the JSON at the server. The object doesn't exist on the server to deserailize into and JSON.net throws parse errors when I try the following:
// Both throw parse errors
JObject o = JObject.Parse(Request.Form.ToString());
JsonConvert.DeserializeObject<MobileEvents>(Request.Form.ToString());
the JSON:
{
"CreateEvents": {
"Event": [
{
"Id": "1",
"Subject": "Hire a Clown"
}
],
"Relationship": [
{
"Primary": "Table1",
"Secondary": "Table2",
"Field": [
{
"Table1Id": "1",
"Table2Id": [
"101"
]
}
]
},
{
"Primary": "Table1",
"Secondary": "Table3",
"Field": [
{
"Table1Id": "1",
"Table3Id": [
"200025"
]
}
]
},
{
"Primary": "Table1",
"Secondary": "Table4",
"Field": [
{
"Table1Id": "1",
"Table4Id": [
"3"
]
}
]
}
]
}
}
Request.Form.ToString() would returns the result like "a=1&b=3", it's definitely not what you need.
If you're passing values as submiting a form, you can use Request.Form["your-key"] to get the value.
If you're passing values by the http body, you can use new StreamReader(Request.InputStream).ReadToEnd() to get the whole JSON string.
I think you have an error within your getting ...
It's not
this.Request.Form.ToString(); // see http://stackoverflow.com/questions/7065979/why-is-the-return-value-of-request-form-tostring-different-from-the-result-of for output
Instead it should be
this.Request.Form["myInputNAME"].ToString();
Important - really use the name-attribute of your input/select/...-element
Anyways: I would like to encourage you, to use eg. <asp:HiddenField runat="server" ID="foo" />. When you have a server-control you can then access its value by simple doing this.foo.Value at server-side, whereas at client-side you can access the input field like document.getElementById('<%= this.foo.ClientID %>')

Categories

Resources