How to simply parse JSON string from a website to C# - 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}");

Related

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

C# Json serialize different types

I'm trying to retrieve all data from a JSON file to my C# application.
But now the problem is that the field "info" in my json file is sometimes from the type string but it can also be the type object.
{
[
{
"id":"147786",
"canUpdate":true,
"canDelete":true,
"canArchive":true,
"hasChildren":false,
"info": "Test"
},
{
"id":"147786",
"canUpdate":true,
"canDelete":true,
"canArchive":true,
"hasChildren":false,
"info": [{"id"="1","messages":"true"}]
}
]
}
well my model you can see here below, when there are only strings in my json file i can retrieve the data without any exception but when there are also objects in the info field then i get the error can't convert the value.
Is there a way to fix this on an easy way?
public string id { get; set; }
public string canUpdate { get; set; }
public string info { get; set; }
As an option you can define the info as dynamic:
public dynamic info { get; set; }
Example
Consider the following json string:
string json = #"
[
{ 'P1': 'X', 'P2': 'Y' },
{ 'P1': 'X', 'P2': [
{'P11':'XX', 'P22':'YY'},
{'P11':'XX', 'P22':'YY'}]
}
]";
You can define such model to deserialize it:
public class C
{
public string P1 { get; set; }
public dynamic P2 { get; set; }
}
And deserialize it like this:
var obj = JsonConvert.DeserializeObject<C[]>(json);
Note
If the number of dynamic properties is too much then usually there is no point in creating the class and the following code will be enough:
var obj = (dynamic)JsonConvert.DeserializeObject(json);

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

RestSharp - deserialize json response with invalid key name (contains a period )

I've been stuck on this for awhile. I have a JSON response sending me keys that include periods. For example: "cost_center.code"
How can I get this into my object? I'm not getting any errors but the value is just coming in as null and isn't being deserialized into my class.
Here's my classes:
public class Result
{
public string company { get; set; }
public string first_name { get; set; }
public string email { get; set; }
public string employee_id { get; set; }
public string last_name { get; set; }
[DeserializeAs(Name="cost_center.code")]
public string cost_center { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
}
Here's the JSON response:
{
"result": [
{
"company": "My Company",
"first_name": "First",
"email": "example#fakeaddress.com",
"employee_id": "123456789",
"last_name": "Last",
"cost_center.code": "12345"
}
]
}
I execute with:
var response = client.Execute<List<RootObject>>(request);
// this returns null
Console.WriteLine(response.Data[0].result[0].cost_center);
// all other values return fine ex:
Console.WriteLine(response.Data[0].result[0].company);
I've tried both with and without the DeserializeAs. I'm not sure its even working. Am I using this property incorrectly? Is it a container issue with the List?
Edited and accepted the answer below to use JsonProperty. For others who may come along this was the solution.
Added JSON.net nuget.
using Newtonsoft.Json;
Set the JsonProperty as described:
[JsonProperty("cost_center.code")]
Changed my execute to:
var response = client.Execute(request);
Then deserialized it like this:
var jsonResponse = JsonConvert.DeserializeObject<RootObject>(response.Content);
Afterwards I can access the value:
Console.WriteLine(jsonResponse.result[0].CostCenter
Do the following with properties having period in their names :
[JsonProperty("cost_center.code")]
public string CostCenter{ get; set; }
It should work
If you want to user RestSharp natively or couldn't get the Newtonsoft.Json.JsonSerializer support to work (which I couldn't), they just added support for proper deserialization of properties with dots in their names as of 106.1.0.
See my response here: Accessing properties with a dot in their name

Categories

Resources