How to get data value in string C# - c#

I have an object like this. How can I parse the Name Surname from this object?
Object
{
"HasError":false,
"AlertType":"success",
"AlertMessage":"Operation has completed successfully",
"ModelErrors":[],
"Data":{
"Count":1,
"Objects":
[{
"Id":291031530,
"FirstName":"Alp",
"LastName":"Uzan",
"MiddleName":"",
"Login":"alp"
}]
}
}
I'm getting this data to an external api using HttpClient but I can't parse it by values. Can you help with this, the type of data is System.String

You have a couple of options. The most type-safe way would be to define C# classes which represent the schema of your JSON content and then deserialise into an instance of those like so:
public class Data
{
public int Count { get; set; }
public List<DataObject> Objects { get; set; }
}
public class DataObject
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Login { get; set; }
}
public class MyJSONObject
{
public bool HasError { get; set; }
public string AlertType { get; set; }
public string AlertMessage { get; set; }
public Data Data { get; set; }
}
...
//Deserialise
var json = "<snip>";
var deserialised = JsonSerializer.Deserialize<MyJSONObject>(json);
//Extract the info you want
Console.WriteLine(deserialised.Data.Objects[0].LastName);
A second, more quick and dirty way to do it would be to parse the JSON into a JsonObject (this is using System.Text.Json) and then extract out the info you need:
var jsonObj = JsonObject.Parse(Properties.Resources.JSON);
var objectsArray = ((JsonArray)y["Data"]["Objects"]);
Console.WriteLine(objectsArray[0]["LastName"]);
A similar method would work with Newtonsoft.Json as well, although you'd need to use JObject instead of JsonObject and JArray rather than JsonArray in that case.

If you use c#, save output in string and serialize, usa this library
using Newtonsoft.Json;
JObject json = JObject.Parse(str);
string Name= json.Data.Objects[0].FirstName
string Surname = json.Data.Objects[0].Lastname

If you are using System.Text.Json:
var jsonObject= JsonSerializer.Deserialize<JsonObject>(jsonString);
Then you can use jsonObject["Data"]["Objects"][0]["FirstName"] to get the data.

Related

retrive specific data from nested json string

I have a block of JSON as follows:
{
"FirstName": "JON",
"LastName": "BAYN",
"Data": [
{
"Plan": "DAY"
}
]
}
I have built it using JavaScriptSerializer like
JavaScriptSerializer serializer_user = new JavaScriptSerializer();
dynamic jsonObject = serializer_user.Deserialize<dynamic>(content_);
dynamic firstname = jsonObject["FirstName"];
firstname = jsonObject["FirstName"];
But I am not able to read from nested "Details" >> "Plan". I've been unable to piece together how to accomplish this goal.
At first, make model class to your json schema:
public class Rootobject
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public int MemberID { get; set; }
public Detail[] Details { get; set; }
}
public class Detail
{
public string Plan { get; set; }
public string Product { get; set; }
public DateTime ProductStartDate { get; set; }
public DateTime ProductEndDate { get; set; }
public string Flag { get; set; }
}
Now you can deserialize your json string to RootObject (Use Json.NET instead of JavaScriptSerializer because it is faster etc):
using Newtonsoft.Json;
..
// If Json.NET is not option:
// var obj = new JavaScriptSerializer().Deserialize<Rootobject>(json)
var obj = JsonConvert.DeserializeObject<Rootobject>(json);
And now you are able to access object structure like following:
if (obj.Details != null)
{
foreach (var detail in obj.Details)
{
Console.WriteLine(detail.Plan);
}
}
If you don't want to create new classes for it and deserialize it, you could just do a regex.

Deserialize Object into a class does not work

I am trying to set a class for a token using DeserializeObject from the json object i get back from my api. However when i run the below code it sets all the values to null or 0, not the result i am getting from the api.
cs code
var resultString = await result.Content.ReadAsStringAsync();
var post = JsonConvert.DeserializeObject<Token>(resultString);
class
public class Token : ContentPage
{
public int StaffID { get; set; }
public string TokenApi { get; set; }
public string StaffForename { get; set; }
public string StaffSurname { get; set; }
public string StaffEmail { get; set; }
public int PrimaryStaffRoleID { get; set; }
}
JSON response
"{\"code\":201,\"status\":\"Success\",\"message\":\"Object found\",\"data\":{\"StaffID\":14,\"StaffSurname\":\"Test\",\"StaffForename\":\"Test\",\"StaffEmail\":\"test#test.com\",\"PrimaryStaffRoleID\":5,\"TokenApi\":\"testToken\"}}"
Firstly the data which you are trying to map is inside another property in your json called Data and secondly your json does not have a property with name Token
The problem actually is you are not using the correct type that reflects your json, means you don't have correct c# type which would get mapped to json, you can generate correct types using json2charp.com , the correct classes for it are :
public class Data
{
public int StaffID { get; set; }
public string StaffSurname { get; set; }
public string StaffForename { get; set; }
public string StaffEmail { get; set; }
public int PrimaryStaffRoleID { get; set; }
public string TokenApi { get; set; }
}
public class RootObject
{
public int code { get; set; }
public string status { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
Now deserializing using RootObject as type parameter would work perfectly fine like:
var resultString = await result.Content.ReadAsStringAsync();
var post = JsonConvert.DeserializeObject<RootObject>(resultString);
A more good option is to use QuickType.IO which would even generate code for you in c# or any other language that they are supporting.
If you analyze the JSON that you posted, the object that you're trying to Deserialize is inside the "data" property of your json.
I suggest you creating a class to represent the JsonResponse with a Data property. This will be your Token
You are retrieved a string that match this object
public string code {get;set;}
public string Success {get;set;} ...
And Token is matching data in json, so
var post = JsonConvert.DeserializeObject<Token>(resultString.data);
would be better.

Deserialize JSON to class in C#

If my string(json) contain only following part, I am able to deserialize it with the help of newtonsoft's library.
{"Code": "MXXXXX", "Status": "failed"}
Code to deserialize:
public class Account
{
public string Code{ get; set; }
public string Status{ get; set; }
}
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Code);
But if my string is like this:
{'data': ' {"Code": "MXXXXX", "Status": "failed"}'}
I am unable to deserialize. Here the class has only one property which is data... how can I do that?
You will need another class for that which wraps the actual account , like:
public class Account
{
public Data Data { get; set };
}
public class Data
{
public string Code{ get; set; }
public string Status{ get; set; }
}
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account .Data.Code);
Try this
public class Account
{
public string Code { get; set; }
public string Status { get; set; }
}
public class AccountWrapper
{
[JsonProperty(PropertyName = "data")]
public string Data { get; set; }
public Account Account
{
get { return JsonConvert.DeserializeObject<Account>(Data); }
}
}
// DeserializeObject
string data = "{'data':'{\"Code\":\"MXXXXX\",\"Status\":\"failed\"}'}";
var account = JsonConvert.DeserializeObject<AccountWrapper>(data).Account;
You could deserialize the whole json as JObject, and then parse part of it into Account:
JObject wholeJson = JObject.Parse(json);
JToken dataToken = wholeJson.GetValue("data");
Account account = dataToken.ToObject<Account>();
My suggestion is that, You can prepare the same object as of the json structure. Like,
public class Test
{
public string data{ get; set; }
}
you can get data out of the object and deserialize it as your doing it now.
Or read it in JObject and then get the data and deserialize it.

How can I convert JSON to an object?

I'm very new to C# and playing around with Visual Studio and Xamarin.
I have a web service where I get a JSON result from looking like this:
{"Vorname": "MYNAME", "AusweisNr": "894", "MitgliedsNr": "33203", "returnstr": "None", "returncode": "0"}
What I'm trying to do is to use the data I get to fill some text fields with, but I don't understand how to get it converted. I've already played around a bit with JsonConvert but couldn't get it working.
Create a class with those properties:
public class SomeMeaningfulName
{
public string Vorname { get; set; }
public string AusweisNr { get; set; }
public string MitgliedsNr { get; set; }
public string returnstr { get; set; }
public string returncode { get; set; }
}
Then you can deserialize the string into that class:
var myObj = JsonConvert.DeserializeObject<SomeMeaningfulName>(yourJsonString);
You can create a simple class like this:
public class Person
{
public string Vorname { get; set; }
public string AusweisNr { get; set; }
public string MitgliedsNr { get; set; }
public string returnstr { get; set; }
public string returncode { get; set; }
}
And to deserialize it:
string json = "{'Vorname': 'MYNAME', 'AusweisNr': '894', 'MitgliedsNr': '33203', 'returnstr': 'None', 'returncode': '0'}"
Person person = new JavaScriptSerializer().Deserialize<Person>(json);
In this case I use JavascriptSerializer because it very simple to use but you can also use JSONConverter if you realy need it
In order to convert using JsonConvert, you need to have a class with fields that share the names of your JSON object and they all need to be public. Try this
class MyJsonObject
{
public string Vorname;
public int AusweisNr;
public int MitgliedsNr;
public string returnstr;
public int returncode;
}
If you want, you could also make it a public property rather than a variable. To convert, you need to do something like this.
MyJsonObject obj= JsonConvert.DeserializeObject<MyJsonObject>(jsonData);
Where jsonData is a string containing your JSON code. You can then copy all the data to a text field.
Get your JSON string and set in this WebSite, this website will create a class object for you, take this object and put in your project.
example:
public class RootObject // object name
{
//atributtes names
public string Vorname { get; set; }
public string AusweisNr { get; set; }
public string MitgliedsNr { get; set; }
public string returnstr { get; set; }
public string returncode { get; set; }
}
So you will dowloand this JSON and put in a String var
example:
var Apiurl = "http://youAPI.com/something/something/";
var JSONString= new System.Net.WebClient().DownloadString(Apiurl);//this will download all text what the Apiurl return
After that, you will put convert/Deserialize your JsonString in a object.
RootObject objectJSON = JsonConvert.DeserializeObject<RootObject>(JSONString);
whats happen in this last code?
yourJsonObject nameForThisObject = JsonConvert.DeserializeObject<yourObjectJsonClass>(yourJsonString);
note: your ObjectJsonClass(my RootObject) must have the sames Json's attributes.

How do I deserialize a JSON array using Newtonsoft.Json

[
{
"receiver_tax_id":"1002",
"total":"6949,15",
"receiver_company_name":"Das Company",
"receiver_email":"info#another.com",
"status":0
},
{
"receiver_tax_id":"1001",
"total":"39222,49",
"receiver_company_name":"SAD company",
"receiver_email":"info#mail.com",
"status":1
}
]
Hi, this is my Json data, but I can't deserialize it.
I want to check only "status" value. (first object "status" 0, second object "status" 1).
Example definition:
public class Example
{
[JsonProperty("receiver_tax_id")]
public string receiver_tax_id { get; set; }
[JsonProperty("total")]
public string total { get; set; }
[JsonProperty("receiver_company_name")]
public string receiver_company_name { get; set; }
[JsonProperty("receiver_email")]
public string receiver_email { get; set; }
[JsonProperty("status")]
public int status { get; set; }
}
Deserialization code:
var des = (Example)JsonConvert.DeserializeObject(responseString, typeof(Example));
Console.WriteLine(des.status[0].ToString());
Try this code:
public class Receiver
{
public string receiver_tax_id { get; set;}
public string total { get; set;}
public string receiver_company_name { get; set;}
public int status { get; set;}
}
And deserialize looks like follows:
var result = JsonConvert.DeserializeObject<List<Receiver>>(responseString);
var status = result[0].status;
If you only care about checking status you can use the dynamic type of .NET (https://msdn.microsoft.com/en-us/library/dd264741.aspx)
dynamic deserialized = JObject.Parse(responseString);
int status1 = deserialized[0].status;
int status2 = deserialized[1].status;
//
// do whatever
This way you don't even need the Example class.
From your code and JSON sampels it seems the problem is you're actually deserializing a List<Example> rather than a single Example.
I would do two things:
Make your class follow .NET naming conventions, as you already prefixed them with the proper JsonProperty attributes:
public class Example
{
[JsonProperty("receiver_tax_id")]
public string ReceiverTaxId { get; set; }
[JsonProperty("total")]
public string Total { get; set; }
[JsonProperty("receiver_company_name")]
public string ReceiverCompanyName { get; set; }
[JsonProperty("receiver_email")]
public string ReceiverEmail { get; set; }
[JsonProperty("status")]
public int Status{ get; set; }
}
Deserialize a List<Example> using the generic JsonConvert.DeserializeObject<T> overload instead of the non-generic version you're currently using:
var des = JsonConvert.DeserializeObject<List<Example>>(responseString);
Console.WriteLine(des[0].Status);
You're trying to deserialize an array into an Example object. Try doing it to a List instead:
var des = JsonConvert.DeserializeObject(responseString, typeof(List<Example>)) as List<Example>;

Categories

Resources