How to serialize to JSON without using an object
I want to serialize my variables to JSON so I can POST the JSON to an external API. I'd rather not make an separate model just to serialize these values.
It's not possible to use a Dictionary because the structure is not default like "var" : "input"
, I'm struggling because one of the fields is structured like: "entryType" : { "name" : "Monitoring" }
.
Does anyone have an suggestion what's the best approach here?
var number = "MLD2101 0107";
var briefDescription = "Test";
var EntryType = "Monitoring";
Im trying to serialize the variables above into the following JSON:
"number": "MLD2101 0107",
"briefDescription": "Test",
"entryType" : { "name" : "Monitoring" },
Edit
I Found the following solution from NewtonSoft:
JObject jsonObject =
new JObject(
new JProperty("number", number),
new JProperty("briefDescription", briefDescription),
new JProperty("entryType",
new JObject("name" , entryType))
);
2 answers
-
answered 2021-01-18 22:34
Roman Marusyk
If you're using Newtonsoft JSON.NET then try this approach with an anonymous object
string json = JsonConvert.SerializeObject(new { number, briefDescription, entryType = new { name = EntryType } });
for System.Text.Json:
string json = JsonSerializer.Serialize(new { number, briefDescription, entryType = new { name = EntryType } });
-
answered 2021-01-18 22:42
Charlieface
You can actually nest Dictionaries, like so:
var json = JsonConvert.SerializeObject( new Dictionary<string, object> { {"number", "MLD2101 0107"}, {"briefDescription", "Test"}, {"entryType", new Dictionary<string, object> { { "name", "Monitoring" } } });
See also questions close to this topic
-
Convert CSV file data from any language to English in C#
I would like to convert CSV file data from multi languages such as Spanish, Russian, European etc to English language in C# program.
Convert all characters like Ó, É to English characters.
Thanks.
-
I get an error when solving this problem, How can I fix?
I am trying to solve the Climbstairs problem but in reverse, where I want to know the number of steps I have to take to go down.
I can go down 1, 2, 3 or 4 steps at the same time. That is, if I am at step i, I can go down to step i - a for any of the values 1, 2, 3 or 4 of a.
I have the following code but I don't know what happens:
I got this error: System.IndexOutOfRangeException in this line:
steps[i] += steps[i - a];
Why I have this error?
public static int DownStairs(int n) { int[] steps = new int[n + 1]; steps[n] = 1; steps[n - 1] = 1; for (int i = n-2; i>=0; i--) { for(int a = 1; a<=4; a++) { steps[i] += steps[i - a]; } } return steps[n]; } static void Main(string[] args) { int n = 5; DownStairs(n); }
-
How to delete multiple blank lines in a WPF DataGrid imported from an Excel file
I have a WPF DataGrid which I fill with imported data from an Excel file (*. Xlsx) through a class, the problem is that multiple blank lines are added to the end of the DataGrid that I don't see how to delete. I attach my code.
<DataGrid Name="dgvMuros" Height="210" Margin="8" VerticalAlignment="Top" Padding="5,6" ColumnWidth="50" IsReadOnly="False" AlternatingRowBackground="Azure" GridLinesVisibility="All" HeadersVisibility="Column" Loaded="dgvMuros_Loaded" CellEditEnding="DataGrid_CellEditEnding" ItemsSource="{Binding Data}" HorizontalGridLinesBrush="LightGray" VerticalGridLinesBrush="LightGray" > </DataGrid>
With this method I import the data from the Excel file.
public void ImportarMuros() { ExcelData dataFronExcel = new ExcelData(); this.dgvMuros.DataContext = dataFronExcel; txtTotMuros.Text = dataFronExcel.numMuros.ToString(); cmdAgregarMuros.IsEnabled = false; cmdBorrarMuros.IsEnabled = false; cmdImportar.IsEnabled = false; } public class ExcelData { public int numMuros { get; set; } public DataView Data { get { Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook; Excel.Worksheet worksheet; Excel.Range range; workbook = excelApp.Workbooks.Open(Environment.CurrentDirectory + "\\MurosEjemplo.xlsx"); worksheet = (Excel.Worksheet)workbook.Sheets["DatMuros"]; int column = 0; int row = 0; range = worksheet.UsedRange; DataTable dt = new DataTable(); dt.Columns.Add("Muro"); dt.Columns.Add("Long"); dt.Columns.Add("Esp"); dt.Columns.Add("X(m)"); dt.Columns.Add("Y(m)"); dt.Columns.Add("Dir"); for (row = 2; row < range.Rows.Count; row++) { DataRow dr = dt.NewRow(); for (column = 1; column <= range.Columns.Count; column++) { dr[column - 1] = Convert.ToString((range.Cells[row, column] as Excel.Range).Value); } dt.Rows.Add(dr); dt.AcceptChanges(); numMuros = dt.Rows.Count; } workbook.Close(true, Missing.Value, Missing.Value); excelApp.Quit(); return dt.DefaultView; } } }
-
Huge amount of logon attempts when loading a page (without cache)
I notice in the Performance Monitor of Windows Server 2012 that there are spikes in logon attempts per second under Web Service -> Logon Attempts/sec. These spikes go from about 0 to 50.
I've traced this down to a page refresh. Loading a page with no cache that is. An average page load does about 50 requests (images, scripts, etc). Now apparently these 50 requests are shown as logon attempts.
Is this normal?
Note that this page does not require the visitor to be logged in.
-
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3\
When warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60]
Storing keys in a directory '/root/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
No XML encryptor configured. Key {e43b756a-2818-4898-8730-5e8e0f230be7} may be persisted to storage in unencrypted form.
info: IdentityServer4.Startup[0]
Starting IdentityServer4 version 4.1.1+cebd52f5bc61bdefc262fd20739d4d087c6f961f
info: IdentityServer4.Startup[0]
You are using the in-memory version of the persisted grant store. This will store consent decisions, authorization codes, refresh and reference tokens in memory only. If you are using any of those features in production, you want to switch to a different store implementation.
info: IdentityServer4.Startup[0]
Using the default authentication scheme Identity.Application for IdentityServer
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://[::]:8081
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://[::]:8080
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: /app
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.TokenEndpoint for /connect/token
info: IdentityServer4.AspNetIdentity.ResourceOwnerPasswordValidator[0]
Credentials validated for username: muthu
info: IdentityServer4.Validation.TokenRequestValidator[0]
Token request validation success, {
"ClientId": "sdgfsdsgsdg",
"ClientName": "Swagger UI",
"GrantType": "password",
"Scopes": "api",
"AuthorizationCode": "********",
"RefreshToken": "********",
"UserName": "sample",
"Raw": {
"grant_type": "password",
"username": "sample",
"password": "REDACTED"
}
}
fail: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3]
Exception occurred while processing message.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'http://*:8080/.well-known/openid-configuration'.
---> System.UriFormatException: Invalid URI: The hostname could not be parsed.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
fail: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[0]
IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'http://*:8080/.well-known/openid-configuration'.
---> System.UriFormatException: Invalid URI: The hostname could not be parsed.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler.HandleAuthenticateAsync()
info: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[7]
Bearer was not authenticated. Failure message: IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
info: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[12]
AuthenticationScheme: Bearer was challenged.
-
ASP.NET using return RedirectToAction(" ", " ") how to use this to redirect to a cshtml
I can not find a useable tutorial that explains how to redirect using REdirectToAction. can someone share a link that that explains ALL the steps needed to use this? I think I am having a hard time understanding how the parameters are given can find an HTML file with a model in the parameter? or is it a controller? I am very lost on how they communicate. please someone if you can help.
-
How to match two values in MongoDB collection query?
Here is my json code
"_id" : ObjectId("6018430823544f4550724308"), "ownerId" : ObjectId("5fd471605dfe592674888e3b"), "screen" : { "ScreenName" : "Aud1", "Seats" : "200" }, "shows" : [ { "showid" : ObjectId("601a16763028260ce88428f1"), "MovieName" : "Joker", "Format" : "2D", "Language" : "English", "Date" : "1/3/2021", "ShowTime" : "2pm", "Vip" : "400", "Premium" : "300", "Executive" : "200", "Normal" : "100" }, { "showid" : ObjectId("601a16983028260ce88428f2"), "MovieName" : "Churuli", "Format" : "2D", "Language" : "Malayalam", "Date" : "02/2/2021", "ShowTime" : "5pm", "Vip" : "400", "Premium" : "300", "Executive" : "200", "Normal" : "100" }, { "showid" : ObjectId("603d08f1cdaa7a26f8e17ebd"), "MovieName" : "bigb", "Format" : "2D", "Language" : "Malayalam", "Date" : "1/3/2021", "ShowTime" : "10am", "Vip" : "400", "Premium" : "300", "Executive" : "200", "Normal" : "100" } ] }
here i want to match
moviename==moviename
which user giving anddate==date
which user giving. I want to get the result if this two condition is trueeg:
moviename==joker and date==1/3/2021
expecting result:
{ "showid" : ObjectId("601a16763028260ce88428f1"), "MovieName" : "Joker", "Format" : "2D", "Language" : "English", "Date" : "1/3/2021", "ShowTime" : "2pm", "Vip" : "400", "Premium" : "300", "Executive" : "200", "Normal" : "100" }
-
update part of a value of a json object using JQ
Have a value inside a JSON object with a variable that needs to be updated using JQ, below is my son file and jq command I'm using to update accountid in json file
{"bucketname":"test/$accountid/123","objectname":"test/$accountid/123","targetlocation":"$TARGET_LOCATION"}
JQ Command
jq 'map(.$accountid = "123")' myjson.json
Error
jq: error (at myjson.json:1): Cannot index string with string "$accountid"
I'm I missing something here?
-
ObjectMapper for multiple naming strategies
I am dealing with a dataset where both underscores and hyphens are being used between tokens in property names:
{ "id" : "116", "priority" : 3, "table_id" : 0, "hard-timeout" : 0, "match" : { "ethernet-match" : { "ethernet-type" : { "type" : 2048 } }, "ipv4-destination" : "10.0.0.25/32" }, "strict" : false, "flow-name" : "port_X_to_8_ip", "instructions" : { "instruction" : [ { "order" : 0, "apply-actions" : { "action" : [ { "order" : 1, "output-action" : { "max-length" : 60, "output-node-connector" : "8" } } ] } } ] },
Notice most elements have hyphens, but a few use underscores, such as
table_id
.On the Java side, I am using this code to create my mapper:
import com.fasterxml.jackson.databind.json.JsonMapper; ... JsonMapper jsonMapper = JsonMapper.builder().configure(SerializationFeature.INDENT_OUTPUT, true).build(); jsonMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // <-- combine this jsonMapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE); // <-- with this?
The last two lines are my current crux. I want the naming strategy to work for either
SNAKE_CASE
orKEBAB_CASE
however I don't see a way toor
the properties and can't find much on google.