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

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

Related

Custom JSON Serialize with custom mapping C#

I want to serialize/deserialize the following JSON:
{
"result": {
"ID": 1,
"TITLE": "Example",
"ARRAY": [
{
"Item1": "Result1",
"Item2": "Result2"
}
]
}
}
I tried with the following class format, but no sucess yet... Can someone help me deserialize it?
public class myClass
{
public string ID { get; set; }
[JsonProperty("TITLE")]
public string Name { get; set; }
}
obs.: Using the namespace Newtonsoft.JSON
In your example class definition above, you have called the class myClass but you would have had to call it result because ID and TITLE are members of the result JSON in the given example. myClass would not resolve to anything.
I don't know why you'd want to have a property called Name that is mapped to TITLE, but ok, if you want to do that you can modify the solution after you get it working.
Still, we're not done yet. You also have a JSON member called ARRAY and you need to define a separate class for that.
And still there is an additional problem: the result JSON is nested inside an implicit base object, so we need to define that as well. Let's call it BaseResult.
public class ARRAY
{
public string Item1 { get; set; }
public string Item2 { get; set; }
}
public class Result
{
public int ID { get; set; }
public string TITLE { get; set; }
public List<ARRAY> ARRAY { get; set; }
}
public class BaseResult
{
public Result result { get; set; }
}
If you are using Visual Studio, you can copy your JSON and paste it in any *.cs file with Edit > Paste Special > Paste JSON as Classes. It will generate POCO objects representing your JSON, which in your case will be this:
public class Rootobject
{
public Result result { get; set; }
}
public class Result
{
public int ID { get; set; }
public string TITLE { get; set; }
public ARRAY[] ARRAY { get; set; }
}
public class ARRAY
{
public string Item1 { get; set; }
public string Item2 { get; set; }
}
Then, asuming that you have your JSON in a string variable named data, you can deserialize it as follows:
var result= JsonConvert.DeserializeObject<Rootobject>(data);

Converting JSON to Object fails - Cannot deserialize the current JSON object into System.Collections.Generic.List

I'm using the API of www.textlocal.in, which returns a JSON formatted object.
JSON
{
"warnings":[
{
"message":"Number is in DND",
"numbers":"917000000000"
}
],
"balance":900,
"batch_id":311110011,
"cost":1,
"num_messages":1,
"message":{
"num_parts":1,
"sender":"TXTLCL",
"content":"Test1"
},
"receipt_url":"",
"custom":"",
"inDND":[
"917000000000"
],
"messages":[
{
"id":"1350123781",
"recipient":918819437284
}
],
"status":"success"
}
My code with which I'm trying to parse the JSON:
private void button1_Click(object sender, EventArgs e)
{
var a = JsonConvert.DeserializeObject<List<jsonToObj[]>>(richTextBox1.Text);
}
public class jsonToObj
{
public warnings[] warnings { get; set; }
public int balance { get; set; }
public int batch_id { get; set; }
public int cost { get; set; }
public int num_messages { get; set; }
public message message { get; set; }
public string receipt_url { get; set; }
public string custom { get; set; }
public messages[] messages { get; set; }
public string status { get; set; }
}
public class warnings
{
public string message { get; set; }
public string numbers { get; set; }
}
public class messages
{
public string id { get; set; }
public int recipient { get; set; }
}
public class message
{
public int num_part { get; set; }
public string sender { get; set; }
public string content { get; set; }
}
I'm getting an exception with the following message:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the
current JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[WindowsFormsApp1.Form2+jsonToObj[]]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly. To fix this error either change the JSON to a JSON array
(e.g. [1,2,3]) or change the deserialized type so that it is a normal
.NET type (e.g. not a primitive type like integer, not a collection
type like an array or List) that can be deserialized from a JSON
object. JsonObjectAttribute can also be added to the type to force it
to deserialize from a JSON object. Path 'warnings', line 1, position
12.'
First of all you have to figure out what your API returns.
Right now you're trying to parse a List of jsonToObj Arrays (List<jsonToObj[]>). You have to decide whether to use a jsonToObj[] or List<jsonToObj> or a simple jsonToObj which your API provides now:
var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);
But this then throws:
JSON integer 918819437284 is too large or small for an Int32. Path 'messages[0].recipient', line 25, position 33."
So make sure you use a Long for that.
public class messages
{
public string id { get; set; }
public long recipient { get; set; }
}
Furthermore you can add inDND to your jsonToObj class if you need the info:
public class jsonToObj
{
...
public string[] inDND { get; set; }
...
}
Based on string you class structure should be like this :
public class Warning
{
public string message { get; set; }
public string numbers { get; set; }
}
public class Message
{
public int num_parts { get; set; }
public string sender { get; set; }
public string content { get; set; }
}
public class Message2
{
public string id { get; set; }
public long recipient { get; set; }
}
public class RootObject
{
public List<Warning> warnings { get; set; }
public int balance { get; set; }
public int batch_id { get; set; }
public int cost { get; set; }
public int num_messages { get; set; }
public Message message { get; set; }
public string receipt_url { get; set; }
public string custom { get; set; }
public List<string> inDND { get; set; }
public List<Message2> messages { get; set; }
public string status { get; set; }
}
It looks like your class structure is not proper, Make use of visual studio and generate C# class from json string and then using that generated class try to deserialize class.
Read : Visual Studio Generate Class From JSON or XML
I simulated your problem and made the following changes that worked:
Change the method that deserializes to this:
var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);
The result of the JSON you receive is not a List, so it will not work to deserialize to List<>.
The recipient property of the messages class receives values larger than an integer, so it must be transformed into a long like this:
public long recipient { get; set; }
These changes solve your problem.
Looks like this is a very old post, still thought of answering.
First of all, your Json data is singular which means, either
var a = JsonConvert.DeserializeObject<List<jsonToObj[]>>(richTextBox1.Text);
or
var a = JsonConvert.DeserializeObject<List<jsonToObj>>(richTextBox1.Text);
may not work for you.
You can either try:
var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);
or
enclose the data with [ and ], which would do the trick.
make sure your parsing single object vs list of objects.

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 to convert an irregular JSON to dictionary or object?

I know hot to Deserialize JSONs like { "key1": "value1", "key2": "value2"}
But now I am trying to use instagram API and it returns me a Json in this form
{
"access_token": "fb2e77d.47a0479900504cb3ab4a1f626d174d2d",
"user": {
"id": "1574083",
"username": "snoopdogg",
"full_name": "Snoop Dogg",
"profile_picture": "..."
}
}
Since it is not structured like an array of keys and values I am confused.
I need to assign those values to the following class of mine.
public class AccessTokenResult
{
public string AccessTokenString { get; set; }
public class UserWhoTook
{
public int ID { get; set; }
public string UserName { get; set; }
public string FullName { get; set; }
}
}
Checkout JsonConvert and questions like Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class
I reccomend you use http://json2csharp.com/ to format your Objects. Just paste in the json and it should spit out the classes for you.
For example, the json you posted generated.
public class User
{
public string id { get; set; }
public string username { get; set; }
public string full_name { get; set; }
public string profile_picture { get; set; }
}
public class RootObject
{
public string access_token { get; set; }
public User user { get; set; }
}
You can use third party libraries for JSON, for example Newton Json.net: https://json.codeplex.com/

JavaScriptSerializer deserialize multiple JSON arrays in single string

In short, I have a client Windows Forms app that receives a Json string from an API in the following form:
string textResult = "{"Data":[{"ID":"G0000013","M_CurBalanceOutstanding":52408.5}],"DataDetail":[{"ErrorDate":"\/Date(1410179960809+0200)\/","ErrorID":1,"ErrorInfo":"Success"}]}"
or formatted via http://www.jsoneditoronline.org/
{
"Data": [
{
"ID": "G0000013",
"M_CurBalanceOutstanding": 52408.5
}
],
"DataDetail": [
{
"ErrorDate": "/Date(1410164281557+0200)/",
"ErrorID": 1,
"ErrorInfo": "Success"
}
]
}
I am trying to de-serialize it like this:
var deserializer = new JavaScriptSerializer();
List<MatterDetailBalOutstanding> results = deserializer.Deserialize<List<MatterDetailBalOutstanding>>(textResult);
where textresult is my JSon string.
I have the following classes:
[DataContract]
class MatterDetailBalOutstanding
{
[DataMember]
public string ID { get; set; }
[DataMember]
public decimal M_CurBalanceOutstanding { get; set; }
[DataMember]
public List<MatterReturnStatusDetails> ErrorData;
public MatterDetailBalOutstanding(string _ID, decimal _M_CurBalanceOutstanding, List<MatterReturnStatusDetails> _ErrorData)
{
ID = _ID;
M_CurBalanceOutstanding = _M_CurBalanceOutstanding;
ErrorData = _ErrorData;
}
}
and:
[DataContract]
class MatterReturnStatusDetails
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Info { get; set; }
[DataMember]
public DateTime Date { get; set; }
public MatterReturnStatusDetails(int _ID, string _Info, DateTime _Date)
{
ID = _ID;
Info = _Info;
Date = _Date;
}
}
I just cannot get it to work? To my understanding it is possible to de-serialize a string containing two JSon arrays. I have read a ton of threads, and a lot of them suggest using another serializer. I have to go with JavaScriptSerializer though. Please could someone help with this? What am I doing wrong? Where am I missing something?
Update 1:
When I try:
MatterDetailBalOutstanding results = deserializer.Deserialize<MatterDetailBalOutstanding>(textResult);
I get the below error:
No parameterless constructor defined for type of 'ConsumeTestWCFApp.ConsumeTestWCFApp+MatterDetailBalOutstanding'.
You can use json2csharp to assist you in generating classes suitable for mapping your JSON. Here is the result :
public class Datum
{
public string ID { get; set; }
public double M_CurBalanceOutstanding { get; set; }
}
public class DataDetail
{
public DateTime ErrorDate { get; set; }
public int ErrorID { get; set; }
public string ErrorInfo { get; set; }
}
public class RootObject
{
public List<Datum> Data { get; set; }
public List<DataDetail> DataDetail { get; set; }
}
Then you can annotate and modify the generated classes further as necessary and use it in deserialization :
var result = deserializer.Deserialize<RootObject>(textResult);
This problem:
No parameterless constructor defined for type of
'ConsumeTestWCFApp.ConsumeTestWCFApp+MatterDetailBalOutstanding'.
occurs because your serialized classes do not have a default constructor. By creating a specific constructor like this:
class MatterDetailBalOutstanding
{
public MatterDetailBalOutstanding(string _ID, decimal _M_CurBalanceOutstanding, List<MatterReturnStatusDetails> _ErrorData)
{
...
}
}
you do not get a default constructor and have to add one yourself:
class MatterDetailBalOutstanding
{
public MatterDetailBalOutstanding(string _ID, decimal _M_CurBalanceOutstanding, List<MatterReturnStatusDetails> _ErrorData)
{
...
}
public MatterDetailBalOutstanding()
{
...
}
}
This may not be you biggest problem now, but I didn't see anyone answer that part of the question.

Categories

Resources