How to Deserialize the json object in windows phone 8.1? - c#

I want to bind json obect to my properties When I deserialize the json object and bind into the properties ,properties shows null values,please some one help me to resolve this.
this is my code
string s = "{\"response\":{\"status\":\"fail\",\"content\":{\"user_id\":\"56\",\"first\":\"kiran\",\"last\":\"kumar\",\"username\":\"kirankumar\"},\"msg\":\"shggh\"}}";
var jsonObj = JObject.Parse(s);
response myDeserializedObj = (response)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonObj.ToString(), typeof(response));
this is properties
public class response
{
public string status { get; set; }
public content content { get; set; }
}
public class content
{
public string user_id { get; set; }
public string first { get; set; }
public string last { get; set; }
public string username { set; get; }
}
Thanks,
karthik

I copied you code and tested it in my machine and I could solve your problem
here is the solution
add the following class
public class ResponseWrapper
{
public response response { get; set; }
}
replace your code with the following
string s = "{\"response\":{\"status\":\"fail\",\"content\":{\"user_id\":\"56\",\"first\":\"kiran\",\"last\":\"kumar\",\"username\":\"kirankumar\"},\"msg\":\"shggh\"}}";
response my = JsonConvert.DeserializeObject<ResponseWrapper>(s).response;
I am sure this will work.
UPDATE
Another solution (Which is tested also) and better than the first one
because it is more clean, and in this way you have not to create new wrapper class.
the solution is replace your string with the following string.
and all of your previous code will stay the same
here is the correct JSON string
string s = "{\"status\":\"fail\",\"content\":{\"user_id\":\"56\",\"first\":\"kiran\",\"last\":\"kumar\",\"username\":\"kirankumar\"},\"msg\":\"shggh\"}";
UPDATE 2
in the comments below of this answer you asked a completely a new question.
here is your new question (I copied this from your comments)
public class responseWraper
{
public response response { get; set; }
}
public class response
{
public string status { get; set; }
public content content { get; set; }
}
public class content
{
public Employees Employees { get; set; }
}
public class Employees
{
public string Employee_id { get; set; }
public string Employee_name { get; set; }
public string status { get; set; }
}
and here is how you are trying to deserialize this (also this copied from your comments)
string s = "{\"response\":{\"status\":\"success\",\"content\":{\"Employees\":[{\"Employee_i‌​d\":\"1\",\"Employee_name\":\"Sravan\",\"status\":\"1\"},}]}}}";
response my = Newtonsoft.Json.JsonConvert.DeserializeObject<responseWraper>(s).response;
ANSWER
your code has two problem
the first is you are using the Employees as array in the JSON string, but the type of the Employees property is not an array
the second problem that the JSON string itself is not valid. it has an errors
there is 4 { character but you have 5 } character inside it.
so you have to fix those two problem as the following
public class content
{
public List<Employees> Employees { get; set; }
}
and the string is
string s = "{\"response\":{\"status\":\"success\",\"content\":{\"Employees\":[{\"Employee_id\":\"1\",\"Employee_name\":\"Sravan\",\"status\":\"1\"},]}}}";
and if you have any other question , I will be happy to help you :)

Try your JSON with http://json2csharp.com/.
Your current code would deserialize the following JSON:
{
"status":"fail",
"content":{
"user_id":"56",
"first":"kiran",
"last":"kumar",
"username":"kirankumar"
},
"msg":"shggh"
}
You are missing a root class with a single Property "response" with the type "Response"

Related

Deserialize JSON objects one by one using json.net (XAMARIN)

I'm new to this. I'm using Xamarin in VS2017.
I have a JSON file as follows
[ {
"LEDGERID":1,
"LEDGERNAME":"CASH",
"UNDER":"19",
"CREDIT_PERIOD":"0",
"CREDIT_LIMIT":"0",
"LEDGER_TYPE":"DEBIT",
"OPENBAL":120196.00,
"STATUS":"True",
"USER_GEN":false,
"date":null,
"arabic_name":null},
{
"LEDGERID":2,
"LEDGERNAME":"PURCHASE",
"UNDER":"17",
"CREDIT_PERIOD":"0",
"CREDIT_LIMIT":"0",
"LEDGER_TYPE":"DEBIT",
"OPENBAL":0.00,
"STATUS":"True",
"USER_GEN":false,
"date":null,
"arabic_name":null
}
]
This is a lengthier one but i made it short for easy understanding. I need to take it one by one because sometimes I need to give test cases before taking the values to the list. I am using PCL storage in XAMARIN tostore the Json File. I went througn the documents of NewtonSoft Json deserializing. I hope some one can help me thanks in advance
Your json isn't valid, you had the word nul, however i'm sure it was a mistake
Take your json to http://json2csharp.com/ and create a class from it and call it what ever you want
Get your self the Json.net Nuget package
Example class
public class RootObject
{
public int LEDGERID { get; set; }
public string LEDGERNAME { get; set; }
public string UNDER { get; set; }
public string CREDIT_PERIOD { get; set; }
public string CREDIT_LIMIT { get; set; }
public string LEDGER_TYPE { get; set; }
public double OPENBAL { get; set; }
public string STATUS { get; set; }
public bool USER_GEN { get; set; }
public object date { get; set; }
public object arabic_name { get; set; }
}
Usage
var results = JsonConvert.DeserializeObject<List<RootObject>>(json);

Understanding how to bind a JSON string into a list of objects in C#?

I'm trying to convert a string into a list of objects in C#. I've written the following:
My input string is something of the following:
[{"channelID":"15","thresh":"30"},{"channelID":"28","thresh":"14"}]
I'm doing the convering using json.net
var deserializedResultList = JsonConvert.DeserializeObject<TriggerDataList>(result);
Now this is where I start to get hazy. I attempted the following class properties to no avail.
class TriggerDataList
{
[JsonProperty("Triggers")]
public List<TriggerData> Triggers { get; set; }
}
class TriggerData
{
public string channelID { get; set; }
public string thresh { get; set; }
}
Is it possible to bind that result to a List of TriggerData objects?
Since I tried your code on a clean solution, I will post exactly what I did as an answer rather than comment:
string json = "[{ \"channelID\":\"15\",\"thresh\":\"30\"},{ \"channelID\":\"28\",\"thresh\":\"14\"}]";
List<TriggerData> deserializedResultList = JsonConvert.DeserializeObject<List<TriggerData>>(json);
And the class (remember to make it public):
public class TriggerData
{
public string channelID { get; set; }
public string thresh { get; set; }
}
The above json (escaped for C#) worked and gave me 2 TriggerData objects in a list.

Deserialize JSON with dynamic objects

I have a JSON object that comes with a long list of area codes. Unfortunately each area code is the object name on a list in the Data object. How do I create a class that will allow RestSharp to deserialize the content?
Here's how my class looks now:
public class phaxioResponse
{
public string success { get; set; }
public string message { get; set; }
public List<areaCode> data { get; set; }
public class areaCode
{
public string city { get; set; }
public string state { get; set; }
}
}
And here's the JSON content:
{
success: true
message: "277 area codes available."
data: {
201: {
city: "Bayonne, Jersey City, Union City"
state: "New Jersey"
}
202: {
city: "Washington"
state: "District Of Columbia"
} [...]
}
Since this JSON is not C# friendly, I had to do a little bit of hackery to make it come out properly. However, the result is quite nice.
var json = JsonConvert.DeserializeObject<dynamic>(sampleJson);
var data = ((JObject)json.data).Children();
var stuff = data.Select(x => new { AreaCode = x.Path.Split('.')[1], City = x.First()["city"], State = x.Last()["state"] });
This code will generate an anonymous type that best represents the data. However, the anonymous type could be easily replaced by a ctor for a more normal DTO class.
The output looks something like this:
your json is incorrect, but if you do correct it you can use a json-to-csharp tool like the one on http://json2csharp.com/ to generate your classes:
public class __invalid_type__201
{
public string city { get; set; }
public string state { get; set; }
}
public class Data
{
public __invalid_type__201 __invalid_name__201 { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
I don't know anything about RestSharp, but if you're using Newtonsoft on the server side, then you can just pass a JObject to your method. Then you can interrogate the object to see what type of object it really is and use JObject.ToObject() to convert it.
I think using Dictionary<int,areaCode> is the easiest way.
public class phaxioResponse
{
public string success { get; set; }
public string message { get; set; }
public Dictionary<int,areaCode> data { get; set; }
public class areaCode
{
public string city { get; set; }
public string state { get; set; }
}
}
Then:
var res= JsonConvert.DeserializeObject<phaxioResponse>(json);
Console.WriteLine(string.Join(",", res.data));

Newtonsoft JSON Deserialize Boolean in List

I'm using the Newtonsoft Json (http://james.newtonking.com/json) library to deserialize some json into an object but having some trouble with a boolean value. Please see my example below. The example should run in LinqPad as long as you reference the Newtonsoft dll (I'm using the latest at the moment which has a file version of 6.0.3.17227). The issue is deserializing into the UpdateLocationsRequest object.
Any help is appreciated.
void Main()
{
string json1 = "{\"token\":\"5b2a38c8-c211-481e-aa75-7d52fff6eb2f\",\"share\":true}";
string json2 = "{\"token\":\"5b2a38c8-c211-481e-aa75-7d52fff6eb2f\",\"locationList\":[{\"desc\":\"This is a test\",\"name\":\"Andrew 3\",\"deviceLocationId\":\"a8d2bfae-4493-41cd-ae1e-ea0da66da0cf\",\"locType\":1,\"lon\":-80.27543,\"lat\":43.42618,\"share\":true}]}";
TestClass req1 = JsonConvert.DeserializeObject<TestClass>(json1);
UpdateLocationsRequest req2 = JsonConvert.DeserializeObject<UpdateLocationsRequest>(json2);
json1.Dump("json1");
req1.Dump("Boolean ok here");
json2.Dump("json2");
req2.Dump("Boolean not ok here. Why not?");
}
// Define other methods and classes here
public class UpdateLocationsRequest
{
public string token { get; set; }
public List<LocationJson> locationList { get; set; }
}
public class LocationJson
{
public string deviceLocationId { get; set; }
public string name { get; set; }
public string desc { get; set; }
public int locType { get; set; }
public float lat { get; set; }
public float lon { get; set; }
public bool show { get; set; }
}
public class TestClass {
public string token {get; set;}
public bool share {get; set;}
}
Your json bool value is share, but in your class it's show. Adjust one or the other so they match, and you should be good to go
I found your problem. You LocationJson class has a boolean property named show whiles your json2 string has the property share. show is never updated. All other values are updated.
It is always a good thing to add breakpoints and step into your program and see what is going on.
Best of luck.

JSON RPC Returns numbers as property names

I receive this JSON string (part of a really big one) back from an oracle server (data is unchangeable) but now I have the tedious problem of not being able to deserialize this..
"rows":[
{
"1":"0000000001",
"2":"SPARE00002",
"5":"151.3354",
"13":"100",
"100000":"000000",
"100001":"FFFFFF",
"rowid":"0000000001"
},
with using NewtonSoft.JSon it creates the class :
public class Row
{
public string __invalid_name__1 { get; set; }
public string __invalid_name__2 { get; set; }
public string __invalid_name__5 { get; set; }
public string __invalid_name__13 { get; set; }
public string __invalid_name__100000 { get; set; }
public string __invalid_name__100001 { get; set; }
public string rowid { get; set; }
}
And while trying to deserialise into the class I get the awesome error :
Could not evaluate expression.
Is there any way to format this correctly so c# realises the string NAME is the same as the property name sent by the JSON string?
Any help is highly appreciated!
EDIT! Found the solution!
By adding [JsonProperty("1")] ..etc to the invalid name strings, the problem solved itself!
Awesome!
On each of the invalid property names, add the attribute: [JsonProperty("1")]

Categories