How to deserialize specific Json - json

Hi guys i try to deserialize a json but this result null , posible its so simple but i cant resolve now , i try this forms, and i use Newtonsoft
if (response.Content.Contains("error"))
{
JObject jObject = JObject.Parse(response.Content);
dynamic x = JsonConvert.DeserializeObject<Error>(response.Content);
error = JsonConvert.DeserializeObject<Error>(response.Content);
JArray recibos = (JArray)jObject["error"];
return error;
}
this its the json my response.content
"{\"error\":{\"code\":-10,\"message\":{\"lang\":\"en-us\",\"value\":\"The warehouse is not defined for the item. [OWOR.Warehouse]\"}}}"
and my class
public class Error
{
public int code { get; set; }
public Message message { get; set; }
public class Message
{
public string lang { get; set; }
public string value { get; set; }
}
}

try this
if (response.Content != null)
{ {
Data data = JsonConvert.DeserializeObject<Data>(response.Content);
}
and add class Data (you can change name)
public class Data
{
public Error error {get; set;}
}

Your Model class is incorrect to which you are trying to de-serialize your JSON string. Change your Model classes to:
public class Message
{
public string lang { get; set; }
public string value { get; set; }
}
public class Error
{
public int code { get; set; }
public Message message { get; set; }
}
public class Root
{
public Error error { get; set; }
}
And your de-serialization will be:
if(string.IsNotNullOrEmpty(response.Content)
{
if (response.Content.Contains("error"))
{
var error = JsonConvert.DeserializeObject<Root>(response.Content);
return error;
}
}
Your error variable will contain the contents of the deserialized result and you can access the required data.
Example working with your JSON string: https://dotnetfiddle.net/NZuwtl

Related

C# JSON deserialization returns null

I'm trying to deserialize some statistics in JSON format from valve's API. The code below doesn't throw any exceptions when deserializing, only when trying to use the statistics afterwards. None of the statistics have a value after deserialization. Valve's response looks like this:
"playerstats":{
"steamID":"",
"gameName":"",
"stats":[
{
"name":"deaths",
"value":5062
}, etc etc..
This is my Rust class (Rust being the game I'm getting statistics from.):
public class Rust
{
public int steamID { get; set; }
public string gameName { get; set; }
public Array stats { get; set; }
}
And this is the deserialization code:
Rust getStats = JsonConvert.DeserializeObject<Rust>(str);
foreach (var stat in getStats.stats) //< ----- Exception: Object reference not set to an instance of an object.
{
parsed += stat.ToString();
}
'parsed' is then returned and used to print out all statistics and 'str' is the json response from Valve. I pasted the entire JSON response on pastebin in-case the above data isn't enough: https://pastebin.com/uJZSTF3G
I've tried naming some of the statistics individually in the Rust class instead of using an Array.
I expect the output to show all of the deserialized statistics for example in a console.
As #Bagus Tesa suggested, try something like...
public class Rust
{
public int steamID { get; set; }
public string gameName { get; set; }
public List<RustStat> stats { get; set; }
}
public class RustStat
{
public string name { get; set; }
public string value { get; set; }
}
Edit
I changed the steamID property to string and added the full code below. This compiled for me successfully. Hope this helps!
public class Valve
{
public Rust playerstats { get; set; }
}
public class Rust
{
public string steamID { get; set; }
public string gameName { get; set; }
public List<RustStat> stats { get; set; }
}
public class RustStat
{
public string name { get; set; }
public string value { get; set; }
}
Valve valve = JsonConvert.DeserializeObject<Valve>(str);
foreach (RustStat stat in valve.playerstats.stats)
{
}

JsonConvert not working on list of structures inside class

Hello i want to deserialize a class which contains a string, a bool and a List<[mystructtype>;When using JsonConvert.Deserialize<[myclass]> it deserializes the string and the bool correctly but not the List<[Struct]>.I have also changed the List<struct> with an array of structs.Both the class container and the struct are marked with Serializeable and i do not understand where the problem is.
Can anyone help me?
Struct
[Serializable]
public struct Status
{
//identifiers
public long playerId { get; set; }
public long groupId { get; set; }
public int type { get; set; }
}
Class Container
[Serializable]
class GatewayDeviceResponse
{
public bool status { get; set; } //gets deserialized good
public string message { get; set; } //gets deserialized good
public Status[] data { get; set; } // all members are defaults
}
Deserialization
IRestResponse response = client.Execute(request);
string result = Encoding.UTF8.GetString(response.RawBytes);
GatewayDeviceResponse resp = JsonConvert.DeserializeObject<GatewayDeviceResponse>(result);
return resp.data.ToList();
P.S The string is a response from a webserver,and i am using RestSharp for creating the server request and getting the response.The thing is the response string is good.The class is deserialized good excluding the collection.
What could the problem be?
P.S
The string response from the server i get is :
"{
\"status\":true,
\"message\":\"ok\",
\"data\":[
{
\"status\":{
\"playerId\":59,
\"groupId\":26,
\"type\":2,
\"deviceId\":\"abababa",
\"groupName\":\"srl\",
\"playerName\":\"Adrian\"
}
},
{
\"status\":{
\"playerId\":25,
\"groupId\":26,
\"type\":1,
\"deviceId\":\"lalal\",
\"groupName\":\"srl\",
\"playerName\":\"Alex\"
}
}
]
}"
The Status[] array elements are not supposed to be fully filled by the server response , just the 3 fields i have posted in the POCO/
I wrote a unit test as below and it passes and correctly deserialized with restsharp. Can you replace your response string and classes to check unit test still pass?
May be your class representation is not fit for your response. Take a little help from http://json2csharp.com/ and check your classes represents your json correctly.
[Test]
public void Can_Deserialize_Struct()
{
var data = "{ \"myList\":[{\"name\": \"test1234\"}] }";
JsonDeserializer json = new JsonDeserializer();
var output = json.Deserialize<MyTest>(new RestResponse { Content = data });
Assert.NotNull(output);
}
class MyTest
{
public List<MyStruct> MyList { get; set; }
}
struct MyStruct
{
public String name { get; set; }
}
According to your response string, your c# classes should represent your json as below :
public class Status
{
public int playerId { get; set; }
public int groupId { get; set; }
public int type { get; set; }
public string deviceId { get; set; }
public string groupName { get; set; }
public string playerName { get; set; }
}
public class StatusData
{
public Status status { get; set; }
}
public class GatewayDeviceResponse
{
public bool status { get; set; }
public string message { get; set; }
public List<StatusData> data { get; set; }
}
It does not related with type struct or class. You need to add another class in front of your status representation class. Because it starts as a json object in your response string.

JSON.NET Error reading string. Unexpected token: StartObject. Path 'responseData',

I am trying to deserialize this link , but I keep getting this error.
Error reading string. Unexpected token: StartObject. Path 'responseData'.
From what i have googled, the problem seems to be the setup of my object I'm trying to deserialize into. Below is my class:
public class FeedSearchResult
{
[JsonProperty("responseData")]
public String ResponseData { get; set; }
[JsonProperty("query")]
public String Query { get; set; }
[JsonProperty("entries")]
public string[] Entries { get; set; }
[JsonProperty("responseDetails")]
public object ResponseDetails { get; set; }
[JsonProperty("responseStatus")]
public String ResponseStatsu { get; set; }
}
public class ResultItem
{
[JsonProperty("title")]
public String Title { get; set; }
[JsonProperty("url")]
public String Url { get; set; }
[JsonProperty("link")]
public String Link { get; set; }
}
What am I doing wrong in my class? Any help would be greatly appreciated.
Your data model only has two levels of nesting, but the JSON returned has three. If you look at the formatted JSON using https://jsonformatter.curiousconcept.com/ you will see:
{
"responseData":{
"query":"Official Google Blogs",
"entries":[
{
"url":"https://googleblog.blogspot.com/feeds/posts/default",
"title":"\u003cb\u003eOfficial Google Blog\u003c/b\u003e",
"contentSnippet":"\u003cb\u003eOfficial\u003c/b\u003e weblog, with news of new products, events and glimpses of life inside \u003cbr\u003e\n\u003cb\u003eGoogle\u003c/b\u003e.",
"link":"https://googleblog.blogspot.com/"
},
In particular your data model has responseData as a String when it needs to be a contained object. This is the specific cause of the exception.
If you upload the JSON to http://json2csharp.com/ you will get the following data model, which can be used to deserialize this JSON:
public class ResultItem
{
public string url { get; set; }
public string title { get; set; }
public string contentSnippet { get; set; }
public string link { get; set; }
}
public class ResponseData
{
public string query { get; set; }
public List<ResultItem> entries { get; set; }
}
public class RootObject
{
public ResponseData responseData { get; set; }
//Omitted since type is unclear.
//public object responseDetails { get; set; }
public int responseStatus { get; set; }
}

JSON parsing in windows phone 8

i am new to windows phone development and so by references implemented some code but i am not able to get the desired result.
i want to parse a JSON that is received as a response from the server.
Please find below my code.
class JSONParsing
{
public Status response { get; set; }
public static void webClient1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (!String.IsNullOrEmpty(e.Result))
{
try
{
JSONParsing root = JsonConvert.DeserializeObject<JSONParsing>(e.Result);
// root is null here
JObject obj = root.response.statusDetail;
// from here it goes to Catch block
foreach (KeyValuePair<string, JToken> pair in obj)
{
string key = pair.Key;
foreach (JObject detail in pair.Value as JArray)
{
string Code = detail["Code"].ToString();
string Msg = detail["Msg"].ToString();
string RegistrationID = detail["RegistrationID"].ToString();
string Name = detail["Name"].ToString();
string Phone = detail["Phone"].ToString();
string email = detail["email"].ToString();
string password = detail["password"].ToString();
}
}
}
catch (Exception ex)
{
Console.WriteLine("Cause of Exception is " + ex.Message);
// exception is-- "Object reference not set to an instance of an object."
}
} // if for empty
}
}
public class Status
{
public string Code { get; set; }
public string Msg { get; set; }
public object RegistrationID { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string email { get; set; }
public string password { get; set; }
[JsonProperty("")]
public JObject statusDetail { get; set; }
}
public class RootObject
{
public List<Status> Status { get; set; }
public int success { get; set; }
}
}
Please Help.
If root is null the class 'JSONParsing' is not having same class structure as the json
and since root is null, accessing property inside a null('root.response.statusDetail') will throw an exception
you can use http://json2csharp.com/ to get the class structure of the json

JavaScriptSerializer Question

I am having some issues DeSerializing the following Json, it runs, throws no errors however the props in the class are all null so it is obviously not working.
{ "realms":[ { "type":"pve", "queue":false, "status":true, "population":"medium", "name":"Malfurion", "slug":"malfurion" } ] }
The above JSON is the jsonResult string so string jsonResult = the above JSON
My code:
public class Realm
{
public string type { get; set; }
public bool queue { get; set; }
public bool status { get; set; }
public string population { get; set; }
public string name { get; set; }
public string slug { get; set; }
}
var realm = javaScriptSerializer.Deserialize<Realm>(jsonResult);
There are no props in the object because the object contains a single array with a single object in the array.