with the web api getting following response, want help to deserialize following json response in vb.net.
{
"data": {
"getReport": {
"report_date": "April 20, 2020",
"report_date_iso": "2020-04-20",
"links": {
"__typename": "Links",
"proportions_diagram": null
},
"results": {
"shape_and_cutting_style": "Emerald Cut",
"data": {
"shape": {
"shape_category": "F"
},
"girdle": null,
"inscription_graphics": []
}
},
"quota": {
"remaining": 4971
}
}
}
}
Thanks in advance
This worked perfect for me on .NET Core 3.1.
To test it:
In Visual Studio 2019, create a winform in .NET Core 3.1. Be sure it has the NuGet package for Newtonsoft.JSON.
Add a button called btnJsonConvTest, and a textbox called txtJSONinput.
Add a new class file to the project - name doesn't matter. Delete standard content from the file.
Select and copy your JSON. In Visual Studio, click Edit > Paste Special > Paste JSON as Classes. This will create the class structure you see below.
Add the bits of code from below. Note that I gave my class the name JSONTestObject.
Run your program, paste your JSON test string into the text box, and click the button.
Code:
using Newtonsoft.Json;
Button click event:
private void btnJsonConvTest_Click(object sender, EventArgs e)
{
JSONTestObject testobj = JsonConvert.DeserializeObject<JSONTestObject>(txtJSONinput.Text);
String res = JsonConvert.SerializeObject(testobj);
MessageBox.Show(res);
}
And the class that VS created for us:
public class JSONTestObject
{
public Data data { get; set; }
}
public class Data
{
public Getreport getReport { get; set; }
}
public class Getreport
{
public string report_date { get; set; }
public string report_date_iso { get; set; }
public Links links { get; set; }
public Results results { get; set; }
public Quota quota { get; set; }
}
public class Links
{
public string __typename { get; set; }
public object proportions_diagram { get; set; }
}
public class Results
{
public string shape_and_cutting_style { get; set; }
public Data1 data { get; set; }
}
public class Data1
{
public Shape shape { get; set; }
public object girdle { get; set; }
public object[] inscription_graphics { get; set; }
}
public class Shape
{
public string shape_category { get; set; }
}
public class Quota
{
public int remaining { get; set; }
}
When I test it, I get the same JSON string back out as went into it, thus proving that both the serialization and deserialization methods correctly move data in and out of the class properties.
Related
I am using Newtonsoft.Json in my C# application and want to know how to extract accountId from following JSON content which stored in string.
Any help is really appreciated.
{ "AccountListResponse": { "Accounts": { "Account": [ {"accountId":"0001","accountIdKey":"key1","accountMode":"ON"}, {"accountId":"00021","accountIdKey":"key21","accountMode":"ON"}, {"accountId":"00031","accountIdKey":"key31","accountMode":"ON"} ] } } }
i tried reading api, but still couldn't find out how to use. becaise of array, it got more complicated.
first here is your model
public class Account
{
public string accountId { get; set; }
public string accountIdKey { get; set; }
public string accountMode { get; set; }
}
public class AccountListResponse
{
public Accounts Accounts { get; set; }
}
public class Accounts
{
public List<Account> Account { get; set; }
}
public class AccountListResponseMain
{
public AccountListResponse AccountListResponse { get; set; }
}
then now you loop through
var regModel = new AccountListResponseMain();
regModel.AccountListResponse =data.AccountListResponse;
for (int a = 0; a < data.Accounts.Length; a++)
{
var inv = new Account();
inv.accountId = a.accountId;
}
N/B not perfect but you get the idea
I have an application that is normally connected to an authentication service that provides an identity for the current user. Often, when I'm travelling or commuting, I don't have internet access and need to work in a local mode. In this environment, I want to hard-code a set of claims into the application using the appSettings file in order to give the current user an identity.
I'm having trouble deserializing the System.Security.Claims structure. I'm using the deserialization method found on this post, but the Configuration system isn't recognizing it. Here's the definition of the class I'm trying to read from the configuration:
public class HttpHost
{
public Uri BaseAddress { get; set; }
[JsonConverter(typeof(ClaimConverter))]
public System.Security.Claims Claim { get; set; }
public string Identifier { get; set; }
public TimeSpan Timeout { get; set; }
}
Here's the actual data:
"HttpHosts": [
{
"BaseAddress": "https://localhost/",
"Claim": {
"Issuer": "LOCAL AUTHORITY",
"OriginalIssuer": "LOCAL AUTHORITY",
"Type": "http://my.org/ws/2015/01/identity/claims/mytype",
"Value": "myvalue",
"ValueType": "http://www.w3.org/2001/XMLSchema#string"
},
"Identifier": "ThetaRex.OpenBook.Desktop.Common.OpenBookHost",
"Timeout": "00:01:23"
}],
How do I get the Configuration system to recognize the custom type converter - ClaimConverter - such that it will work when using it with DI:
public HttpHost(IOptions<List<HttpHost>> options)
{
HttpHost httpHost = options.Value.Find(h => h.Identifier == typeof(T).FullName);
...
}
this code was tested in visual studio and working properly
var appSettingsSection = configuration.GetSection("HttpHosts");
HttpHost[] settings = appSettingsSection.Get<HttpHost[]>();
UPDATE
if you need to use a special class Claims you can convert this claim to your class Claims using a mapper or manually ( you can add this code to getter or setter as well)
var claims=settings[0].ClaimDetails;
settings[0].Claims= new System.Security.Claims { Issuer=claims.Issuer, .... }
classes
public class HttpHost
{
public string BaseAddress { get; set; }
[JsonProperty("Claim")]
public ClaimDetails ClaimDetails { private get; set; }
[JsonIgnore]
public System.Security.Claims Claims { get; set; }
public string Identifier { get; set; }
public string Timeout { get; set; }
}
public class ClaimDetails
{
public string Issuer { get; set; }
public string OriginalIssuer { get; set; }
public string Type { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
I'm using .netcore 3.1 and I'm using System.Text.Json for serialization and deserialization. I didn't know how to phrase my question precisely. I looked around but couldn't find a direct answer for my question.
Apologies if it's a duplicate.
This is a sample JSON response.
{
"properties": {
"subscriptionId": "sub1",
"usageStartTime": "2015-03-03T00:00:00+00:00",
"usageEndTime": "2015-03-04T00:00:00+00:00",
"instanceData": "{\"Microsoft.Resources\":{\"resourceUri\":\"resourceUri1\",\"location\":\"Alaska\",\"tags\":null,\"additionalInfo\":null}}",
"quantity": 2.4000000000,
"meterId": "meterID1"
}
}
I'm interested in directly parsing instanceData.
If you observe closely, instanceData is an embedded JSON string.
{
"Microsoft.Resources": {
"resourceUri": "resourceUri1",
"location": "Alaska",
"tags": null,
"additionalInfo": null
}
}
Question:
Is it possible to parse this instanceData while the whole Json is being parsed? Can we add some Attributes to instanceData field for direct parsing? Right now, I'm accessing the string from the parsed model class and parsing instanceData separately.
This is what I'm doing right now (something like this):
JsonSerializer.Deserialize<MicrosoftResources>(parsedResponse.instanceData).
I have already built model classes for instanceData and other entities. Currently, instanceData is of type string in my root model class.
I'm interested in directly parsing instanceData. If you observe closely, instanceData is an embedded JSON string
Is it possible to parse this instanceData while the whole Json is being parsed?
You can achieve above requirement by creating and using a custom converter, like below.
public class ResConverter : JsonConverter<InstanceData>
{
public override InstanceData Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
//you can implement it based on your actual requirement
//...
string jsonData = reader.GetString();
var instanceData = System.Text.Json.JsonSerializer.Deserialize<InstanceData>(jsonData);
return instanceData;
}
Model Classes
public class MyModel
{
public Properties Properties { get; set; }
}
public class Properties
{
public string SubscriptionId { get; set; }
public DateTimeOffset UsageStartTime { get; set; }
public DateTimeOffset UsageEndTime { get; set; }
[JsonConverter(typeof(ResConverter))]
public InstanceData InstanceData { get; set; }
public double Quantity { get; set; }
public string MeterId { get; set; }
}
public class InstanceData
{
[JsonPropertyName("Microsoft.Resources")]
public MicrosoftResources MicrosoftResources { get; set; }
}
public class MicrosoftResources
{
public string ResourceUri { get; set; }
public string Location { get; set; }
public object Tags { get; set; }
public object AdditionalInfo { get; set; }
}
Test code and result
var jsondata = "{\"Properties\":{\"SubscriptionId\":\"sub1\",\"UsageStartTime\":\"2015-03-03T00:00:00+00:00\",\"UsageEndTime\":\"2015-03-04T00:00:00+00:00\",\"InstanceData\":\"{\\u0022Microsoft.Resources\\u0022:{\\u0022ResourceUri\\u0022:\\u0022resourceUri1\\u0022,\\u0022Location\\u0022:\\u0022Alaska\\u0022,\\u0022Tags\\u0022:null,\\u0022AdditionalInfo\\u0022:null}}\",\"Quantity\":2.4,\"MeterId\":\"meterID1\"}}";
MyModel myModel = System.Text.Json.JsonSerializer.Deserialize<MyModel>(jsondata);
If you can change the instanceData to Json instead of string like this.
{
"properties": {
"subscriptionId": "sub1",
"usageStartTime": "2015-03-03T00:00:00+00:00",
"usageEndTime": "2015-03-04T00:00:00+00:00",
"instanceData": {"Microsoft.Resources":{"resourceUri":"resourceUri1","location":"Alaska","tags":null,"additionalInfo":null}},
"quantity": 2.4000000000,
"meterId": "meterID1"
}
}
You can easily deserialize your Json using the example below.
Model Classes:
public partial class Properties
{
[JsonPropertyName("properties")]
public PropertiesClass PropertiesProperties { get; set; }
}
public partial class PropertiesClass
{
[JsonPropertyName("subscriptionId")]
public string SubscriptionId { get; set; }
[JsonPropertyName("usageStartTime")]
public DateTimeOffset UsageStartTime { get; set; }
[JsonPropertyName("usageEndTime")]
public DateTimeOffset UsageEndTime { get; set; }
[JsonPropertyName("instanceData")]
public InstanceData InstanceData { get; set; }
[JsonPropertyName("quantity")]
public double Quantity { get; set; }
[JsonPropertyName("meterId")]
public string MeterId { get; set; }
}
public partial class InstanceData
{
[JsonPropertyName("Microsoft.Resources")]
public MicrosoftResources MicrosoftResources { get; set; }
}
public partial class MicrosoftResources
{
[JsonPropertyName("resourceUri")]
public string ResourceUri { get; set; }
[JsonPropertyName("location")]
public string Location { get; set; }
[JsonPropertyName("tags")]
public object Tags { get; set; }
[JsonPropertyName("additionalInfo")]
public object AdditionalInfo { get; set; }
}
Usage:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
class Program
{
static void Main(string[] args)
{
// escaped version, just for demo
var json =
"{\r\n \"properties\": {\r\n \"subscriptionId\": \"sub1\",\r\n \"usageStartTime\": \"2015-03-03T00:00:00+00:00\",\r\n \"usageEndTime\": \"2015-03-04T00:00:00+00:00\",\r\n \"instanceData\": {\"Microsoft.Resources\":{\"resourceUri\":\"resourceUri1\",\"location\":\"Alaska\",\"tags\":null,\"additionalInfo\":null}},\r\n \"quantity\": 2.4000000000,\r\n \"meterId\": \"meterID1\"\r\n }\r\n}";
var props = JsonSerializer.Deserialize<Properties>(json);
}
}
Props will have all of the data. I hope this helps.
I've created a Web Service to receive data from Android json.
The json i receive is:
{
"assignmentId":"5476",
"newProductName":"ALGOBOX NET USB",
"Attributes": {
"Ammyy": "fvhbhgfc",
"Database": "h j j i i ",
"Plan": "555555555"
}
}
I want to deserialize the json and although i managed to deserialize the root elements, cannot deserialize the Nested:
"Attributes": {
"Ammyy": "fvhbhgfc",
"Database": "h j j i i ",
"Plan": "555555555"
}
The problem is that the attributes must be dynamic (Ammmy, Database, etc), so i cannot create a class with these strings. I want to deserialize the nested object to a Dictionary or KeyValuePair.
The classes that i've created are these:
public class RequestDataNewProduct
{
public string assignmentId { get; set; }
public string newProductName { get; set; }
public List<Atts> Attributes { get; set; }
}
public class Atts
{
public List<KeyValuePair<string, string>> Attributes { get; set; }
}
Any help?
the C# typed equivalent for your json should look like -
public class Attributes
{
public string Ammyy { get; set; }
public string Database { get; set; }
public string Plan { get; set; }
}
public class RequestDataNewProduct
{
public string assignmentId { get; set; }
public string newProductName { get; set; }
public Attributes Attributes { get; set; }
}
Then just deserialize it -
var t = JsonConvert.DeserializeObject<RequestDataNewProduct>(json); //success
Console.WriteLine(t.Attributes.Ammyy); //fvhbhgfc
I'm trying to make a windows phone application that reads a json file from a website. This json file has a repeating group and I can't seem to get the program to read all the groups.
This is an example of the json output:
{
"program":{
"title":"Carl Schmitz",
"image_url":"http:\/\/q-music.be\/sites\/2009.q-music.be\/files\/NOA.jpg"
},
"noa":[
{
"title":"Behind Blue Eyes",
"artist":"LIMP BIZKIT",
"itunes_link":"http:\/\/clk.tradedoubler.com\/click?p=24379&a=1256924?url=http:\/\/itunes.apple.com\/be\/album\/behind-blue-eyes\/id14915153?i=14915155&uo=4&partnerId=2003"
},
{
"title":"Alone Again",
"artist":"ALYSSA REID",
"itunes_link":"http:\/\/clk.tradedoubler.com\/click?p=24379&a=1256924?url=http:\/\/itunes.apple.com\/be\/album\/alone-again-original-mix\/id496520410?i=496520415&uo=4&partnerId=2003"
}
]
}
Can someone explain me how to read this json?
Your class structure should look something like this. I used the awesome json2csharp to generate it:
Then you should be able to deserialize directly into the RootObject. You didn't mention which serializer you were using, so the actual deserialization isn't shown here (yet).
public class Program
{
public string title { get; set; }
public string image_url { get; set; }
}
public class Noa
{
public string title { get; set; }
public string artist { get; set; }
public string itunes_link { get; set; }
}
public class RootObject
{
public Program program { get; set; }
public List<Noa> noa { get; set; }
}