How to deserialize a JSON in Blazor? - c#

I have a JSON from an API,
{
"Cards":[
{
"ContentType":3,
"Content":"robgra"
},
{
"ContentType":4,
"Content":"Rob Graham"
},
{
"ContentType":1,
"Content":"https://www.mineralblue.net/images/robgra.jpg"
}
]
}
And i am trying to deserialize it in my .razor page. So far I have deserialized it into a string using,
using var responseStream = await response.Content.ReadAsStreamAsync();
APIreturn = await JsonSerializer.DeserializeAsync<string>(responseStream);
But i want to break it up into ConntentType and Content, i've been trying to save it as an IEnumerable object, but i keep getting an error saying the input does not contain any JSON tokens.
For example my code looks like,
Deserialized = await JsonSerializer.DeserializeAsync<IEnumerable<MyObject>>(responseStream);
But i can't figure out how to format my public class object so that i can successfully deserialize it and access individual classes.
I've tried using [JsonPropertyName("Cards"] but it didn't work. How would i format my object so i can deserialize this JSON?

Let VS do the work. Copy your JSON to a class file and use Edit | Paste Special | Paste JSON as classes and ....
public class Rootobject
{
public Card[] Cards { get; set; }
}
public class Card
{
public int ContentType { get; set; }
public string Content { get; set; }
}

Related

How to simply parse JSON string from a website to C#

so I have a problem:
The code in JSON that you see there is a response that a webpage gives me. And the thing I want to do is really simple:
I just want to parse for example the "user_id", or "class".
I tried few things on stackoverflow that I found but no one works...
{
"data": {
"user": {
"class": "user",
"user_id": "81046537",
"etp_guid": "76411082-73ab-5aaa-9242-0bb752cf97a4",
},
},
}
Thanks !
There are many ways you can extract the user_id from the json. The most common way is to use Newtonsoft.Json package.
Assuming the json is stored as a string, you can call JObject.Parse().
var data = "{'data': {'user': {'class': 'user','user_id': '81046537','etp_guid': '76411082-73ab-5aaa-9242-0bb752cf97a4'} } }";
JObject jObject = JObject.Parse(data);
var userId = jObject["data"]["user"]["user_id"];
Console.WriteLine($"User id {userId}");
If your json is stored as a n object, then call JObject jObject = new JObject(data)
A preferred way is to serialise your json using business object. Simply create classes to match the json structure. e.g:
public class Response
{
public Data Data { get; set; }
}
public class Data
{
public User User { get; set; }
}
public class User
{
public string Class { get; set; }
public string User_id { get; set; }
public string Etp_guid { get; set; }
}
Then deserialize your object. e.g:
var response = JsonConvert.DeserializeObject<Response>(data);
Console.WriteLine($"User id {response.Data.User.User_id}");

How to Convert Json to object c# To Post Data APi

{
"user": {
"id": 121,
"username": "luckygirl3",
"counter_rechecking": 0,
"user_id": 76,
"f_Id": "4334"
}
}
How to convert it to object and post it to api. I have already know how to post but I need to post user object with parameters. I tried this:
JObject jobjects = new JObject();
JObject jobjectss = new JObject();
jobjects["user"] = jobjectss;
jobjectss["id"] = 121;
jobjectss["username"] = "luckygirlx3";
jobjectss["counter_rechecking"] = 0;
jobjectss["user_id"] = 76;
jobjectss["f_Id"] = "4334";
How to Convert Json to object c# To Post Data APi
This seems like you want to convert a JSON response to a object. If this is the case then you want to deserialize your JSON. You havn't posted your Post Data code, so I can't help much with that.
I would first map your JSON to classes:
public class User
{
public int Id { get; set; }
public string Username { get; set; }
[JsonProperty("counter_rechecking")]
public int CounterRechecking { get; set; }
[JsonProperty("user_id")]
public int UserId { get; set; }
[JsonProperty("f_id")]
public string FId { get; set; }
}
public class RootObject
{
public User User { get; set; }
}
Then deserialize your JSON to RootObject with Json.NET:
var deserializedJson = JsonConvert.DeserializeObject<RootObject>(json);
You can then access your properties like this:
Console.WriteLine(deserializedJson.User.Id);
Console.WriteLine(deserializedJson.User.Username);
Console.WriteLine(deserializedJson.User.CounterRechecking);
Console.WriteLine(deserializedJson.User.UserId);
Console.WriteLine(deserializedJson.User.FId);
I used JsonProperty to map your attributes with _ to nicer property members. This is optional however.
You can also use something like json2csharp.com or Edit -> Paste Sepcial -> Paste JSON as classes inside Visual Studio after copying your JSON to the clipboard to generate the classes for you.
Full demo at dotnetfiddle.net.

Extract data from json C#

I have a a api response from Azure Ml which returns the follow json bellow:
responseApi content
{ "Results": { "id_unidade_negocio": [ { "msgSucesso": "Processamento concluĂ­do com sucesso" } ] } }
I would like to extract only the "msgSucesso": "Processamento concluĂ­do com sucesso"
I try the code below, however didn't work.
var obj = JObject.Parse(responseApi);
var msg = (string)obj.SelectToken("Results.msgSucesso");
I didin't try to deserialize the json to a object class, because I don't know the right format class to create it to be compatible with output json.
Whats is the best way to extract this info from json response?
Or How can I create a class that fit in this json output in other to convert the json to object?
https://stackoverflow.com/a/24233127/2906166
check above link
public class IdUnidadeNegocio
{
public string msgSucesso { get; set; }
}
public class Results
{
public List<IdUnidadeNegocio> id_unidade_negocio { get; set; }
}
public class RootObject
{
public Results Results { get; set; }
}
var obj = JsonConvert.DeserializeObject<RootObject>(responseApi);
Console.WriteLine(obj.Results.First().msgSucesso);

Parse the fetched data in C#

I am new to C# and trying to write some code to fetch the webpage and parse it into readable format.
I have fetched the data from webpage using uri
var uri2 = new Uri("explame.com")
I see the response in format below like this:
{"name":"abc" "country":"xyz" "citizenship":"A" [{"pincode":"111", "Dis":"no"] Lot's of data follows something like that
There are multiple with attribute "name" and "country" in response. My question is how to fetch the data something like below
name:abc
country:xyz
citizenshih:A
pincode 111
dis:no
For all attributes in response code.
Is that the exact format of the data you're getting? Because that's JSON-ish, but it's not valid JSON and wouldn't be parsed as such. If, however, you are actually getting JSON then you can de-serialize that.
Using something like Newtonsoft's JSON library you can fairly trivially de-serialize JSON into an object. For example, this JSON:
{
"name":"abc",
"country":"xyz",
"citizenship":"A",
"someProperty": [
{
"pincode":"111",
"Dis":"no"
}]
}
Might map to these types:
class MyClass
{
public string Name { get; set; }
public string Country { get; set; }
public string Citizenship { get; set; }
public IEnumerable<MyOtherClass> SomeProperty { get; set; }
}
class MyOtherClass
{
public string Pincode { get; set; }
public string Dis { get; set; }
}
In which case de-serializing might be as simple as this:
var myObject = JsonConvert.DeserializeObject<MyClass>(yourJsonString);
you could try
dynamic data = JsonConvert.DeserializeObject(receivedJsonString);
foreach (dynamic o in data)
{
Debug.WriteLine(o.country);
}

How can I deserialize JSON containing delimited JSON?

I have a problem with deserializing a Json-string to an object.
This is a sample json i receive from a webservice:
{
"GetDataResult":
"{
\"id\":1234,
\"cityname\":\"New York\",
\"temperature\":300,
}"
}
And I have a class CityData that looks like this
[JsonObject("GetDataResult")]
public class CityData
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("cityname")]
public string CityName { get; set; }
[JsonProperty("temperature")]
public int Temperature { get; set; }
}
I try to deserialize the json with a call of the method DeserializeObject
var cityData = JsonConvert.DeserializeObject<CityData>(response);
but the root element seems to make problems...
Do you guys know how I can fix it, so that I receive a CityData-object with the data filled in?
The json response contains an object that within itself contains a json string representing the data result.
You need to deserialize twice, once for the response and one more for the data result.
var response = JsonConvert.DeserializeObject<JObject>(responseStr);
var dataResult = (string)response["GetDataResult"];
var cityData = JsonConvert.DeserializeObject<CityData>(dataResult);

Categories

Resources