Deserialize JSON to class in C# - 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.

Related

How to get data value in string 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.

C# Convert json to multiple classes

I have a problem. I am trying to parse my json to 2 classes. Here is the json:
{
"user":[
[
{
"Id":"0",
"Username":"Vreeswijk",
"ProfilePicture":"media/user/0.png"
}
]
],
"token":[
[
{
"access_token":"myToken1",
"refresh_token":"myToken2",
"expires_in":3600,
"expires_on":1577363756
}
]
]
}
And here are my 2 classes:
public class Token
{
public string access_token { get; set; }
public string refresh_token { get; set; }
public int expire_in { get; set; }
public int expire_on { get; set; }
public Token() { }
}
And here is the user class:
public class User
{
[PrimaryKey]
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string ProfilePicture { get; set; }
public User() { }
public User(string Username, string Password)
{
this.Username = Username;
this.Password = Password;
}
}
Now I want to deserialize the json to those 2 classes.
Here is my code now that works for 1 class only:
var jObject = JObject.Parse(json);
var userPropery = jObject["user"] as JArray;
userList= new List<user>();
foreach (var property in userPropery )
{
var propertyList = JsonConvert.DeserializeObject<List<user>>(property.ToString());
userList.AddRange(propertyList);
}
How can I make this work for 2 classes in 1 json?
If you observe your Json, both user and token are nested Arrays. You can now create Root Class that has both the required properties. For Example
public class Root
{
public List<List<User>> user { get; set; }
public List<List<Token>> token { get; set; }
}
Now, instead of using JObject.Parse you could deserialize it directly as
var root = JsonConvert.DeserializeObject<Root>(json);
To get a flattened user and token list, you can use
var userList= root.user.SelectMany(x=>x);
var tokenList= root.token.SelectMany(x=>x);
You can create a Root class for your json and add two properties in it with User and Token classes as required.
public class Root
{
public List<List<User>> Users { get; set; }
public List<List<Token>> Tokens { get; set; }
}
Then pass this class in DeserializeObject function to deserialize the json.
Why don't you create a class include both user and token?
If you don't do this, please parse one by one.

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.

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.

Json.NET failes to deserialize Json to a field-only class

I want to parse a piece of JSON with Newtonsoft Json.NET
JSON:
{
"USER":{
"result_id":"0",
"result_description":"NET Connections",
"cmlog_username":[
"8118236834",
"8118236834",
"8118236834"
],
"caller_id":[
"14cc20f7b05f",
"14cc20f7b05f",
"14cc20f7b05f"
]
}
}
Class
public class USER
{
public string result_id;
public string result_description;
public string[] cmlog_username;
public string[] caller_id;
}//USER
I convert it with below code but all of property value is NULL
USER con = JsonConvert.DeserializeObject<USER>(msg);
Your deserialization class is incorrect. Putting your JSON into json2csharp.com produces:
public class USER
{
public string result_id { get; set; }
public string result_description { get; set; }
public List<string> cmlog_username { get; set; }
public List<string> caller_id { get; set; }
}
public class RootObject
{
public USER USER { get; set; }
}
So you would need to do:
User con = JsonConvert.DeserializeObject<RootObject>(msg);
Your JSON object isn't a USER, it's an object that contains a USER.
It's because the JSON object you are trying to parse into a user is an object that has a property of 'user' that is a user object. That probably didn't make much sense. You could change your json to be
{
"result_id":"0",
"result_description":"NET Connections",
"cmlog_username":[
"8118236834",
"8118236834",
"8118236834"
],
"caller_id":[
"14cc20f7b05f",
"14cc20f7b05f",
"14cc20f7b05f"
]
}
and it will work.
Try adding the get and set to your class
public class USER
{
public string result_id { get; set; }
public string result_description { get; set; }
public string[] cmlog_username { get; set; }
public string[] caller_id { get; set; }
}//USER

Categories

Resources