Extract data from json C# - 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);

Related

How to deserialize a JSON in Blazor?

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; }
}

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}");

Getting the key value from a JSON object

I am passing an object to a C# winform application via socketIO i manage to get the data, but having trouble getting the key value from the object, so far below is my code to capture the data from the socket server.
socket.On("traverseLeft", (data) =>
{
Invoke(new Action(() =>
{
MessageBox.Show(data.ToString());
}));
});
So my output is below, what I need to get is the interactive_link's value which is "sub", how can I achieve this on C#?
{
"msg":{
"interactive_link":"sub"
}
}
First, download the Newtonsoft NuGet package: Newtonsoft.Json from NuGet.
Then create the following classes:
public class RootObject
{
[JsonProperty("msg")]
public Message Message { get; set; }
}
public class Message
{
[JsonProperty("interactive_link")]
public string InteractiveLink { get; set; }
}
And finally do this:
var inputObj = JsonConvert.DeserializeObject<RootObject>(data);
var message = inputObj.Message.InteractiveLink;
MessageBox.Show(message);
Hope this helps.
You can also use JObject to read the properties
JObject obj = JObject.Parse(json);
Console.WriteLine(obj["msg"]["interactive_link"]);
You can create the model class as per your JSON response. You can create it online using http://json2csharp.com/
public class Msg
{
public string interactive_link { get; set; }
}
public class MyJson
{
public Msg msg { get; set; }
}
And then deserialize your json to this class using Newtonsoft.Json(nuget).
var myJson = JsonConvert.DeserializeObject<MyJson>(json);
And then access your data
var interactiveLink = myJson.msg.interactive_link;
If your data has a defined structure, you can use a Strongly-Typed manner. So you should define your classes first:
public class Msg
{
public string interactive_link { get; set; }
}
public class DataObject
{
public Msg msg { get; set; }
}
And the parse your JSON result to the defined object:
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<DataObject>(data);

Parsing nested json with n number of json objects in c#

i am a newbie to coding , I have a nested json coming from a external source the json format is looks something like this ..
{
"data":"data",
"data":
{
"data":"data",
//----------------e.t.c the internal objects could be in n number
}
}
so how do i deserialize the json object and use the data as a list in order to do my other operations like sql and posting the data??
You need to create a class that is appropriate with the Json, like that:
public someClass
{
public string data1 { get; set; }
public DataClass dataArr { get; set; }
}
public DataClass
{
public string insideData { get; set; }
}
after you do this you need the following code:
var jsonDto = JsonConvert.DeserializeObject<someClass>(yourJson);

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);
}

Categories

Resources