How to deserialize a Json string in c# - json

I have this Json string in memory, and trying to deserialize into a class :
{
{ "Member_ColName": "Entity Name" , "Member_Key": "entityName" },
{ "Margin_ColName": "Margin", "Margin_Key": "Margin" },
{ "LookBack_ColName": "Lookback Interval (Days)", "LookBack_Key":"LookbackInterval"},
{ "ConfInterval": "Confidence Interval"," ConfInterval_Key": "ConfidenceInterval"}
}
My public class is defined as :
public class JsonParameters
{
string Member_ColName { get; set; }
string Member_Key { get; set; }
string Margin_ColName { get; set; }
string Margin_Key { get; set; }
string LookBack_ColName { get; set; }
string LookBack_Key { get; set; }
string ConfInterval { get; set; }
string ConfInterval_Key { get; set; }
}
My c# method is as follows:
public string getJsonParameters()
{
// file stream code omitted
JavaScriptSerializer ser = new JavaScriptSerializer();
string jsonStr = utf.GetString(buffer);
Classes.JsonParameters jsonData = (Classes.JsonParameters)ser.Deserialize(jsonStr, typeof(Classes.JsonParameters));
return jsonStr;
}
I've done this kind of thing before when reading in a string of dates, but I did something slightly different.
In this case I can't seem to deserialize the Json object.
Any advice would be appreciated.
thanks.
Bob

Related

How to read json request body array object?

I am sending data in a post request as follow:
{
"HospitalId": "Hospital-0232",
"DataSliceTimestamp": "2020.08.10",
"HourQuarter": "00:01",
"Data": [
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2014,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"},
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2015,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"},
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2016,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"},
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2017,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"},
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2018,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"}
]
}
And for reading the body I am doing it like this:
public class RequestBody
{
public string HospitalId { get; set; }
public string DataSliceTimestamp { get; set; }
public string HourQuarter { get; set; }
public string[] Data { get; set; }
}
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
RequestBody data = JsonConvert.DeserializeObject<RequestBody>(requestBody);
But I get error:
Newtonsoft.Json: Unexpected character encountered while parsing value: [. Path 'Data', line 5, position 13.
Something is wrong while reading array data, please guide.
You need to strongly type your JSON input to an object array not a string.
Here's an example of what the object could look like:
public class Datum
{
[JsonProperty("country")]
public string country { get; set; }
[JsonProperty("state")]
public string state { get; set; }
[JsonProperty("county")]
public string county { get; set; }
[JsonProperty("lat")]
public double lat { get; set; }
[JsonProperty("lng")]
public double lng { get; set; }
[JsonProperty("type")]
public string type { get; set; }
[JsonProperty("measure")]
public string measure { get; set; }
[JsonProperty("beds")]
public double beds { get; set; }
[JsonProperty("population")]
public int population { get; set; }
[JsonProperty("year")]
public int year { get; set; }
[JsonProperty("source")]
public string source { get; set; }
[JsonProperty("source_url")]
public string source_url { get; set; }
}
public class RequestBody
{
[JsonProperty("HospitalId")]
public string HospitalId { get; set; }
[JsonProperty("DataSliceTimestamp")]
public string DataSliceTimestamp { get; set; }
[JsonProperty("HourQuarter")]
public string HourQuarter { get; set; }
[JsonProperty("Data")]
public IList<Datum> Data { get; set; }
}
You can then deserialize it like you're already doing:
RequestBody data = JsonConvert.DeserializeObject<RequestBody>(requestBody);
I solved this by using dynamic type and by pulling out data field from the request body.
// Reading body
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
// Parse through the request body string and make it in appropriate format.
dynamic RequestBody_data = JsonConvert.DeserializeObject(requestBody);
var Data = RequestBody_data["Data"].ToString();
Through this I was able to get the data field string and then I can split it with "}," to get all the rows. Thanks

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.

Cannot Deserialise Json array into type string

Following id my piece of code which deserialise Json string.
response = "{\"success\":\"yes\",\"error\":\"\",\"message\":\"\",\"arguments\":[{\"id\":\"72820\",\"rowNo\":\"1\",\"userId\":\"40\",\"entityId\":\"3486\",\"value\":\"search Panel\",\"typeCategory\":\"3\"}]}";
erpAPIResponse basicResponse = JsonConvert.DeserializeObject<erpAPIResponse>(response);
Result is JSON string which is deserialised into erpAPIResponse.
My erpAPIResponse is as follows:
public string success { get; set; } // getting and setting the success
public string error { get; set; } // getting and setting the error
public string message { get; set; } // getting and setting the message
public string arguments { get; set; } // getting and setting the arguments
// public string result { get; set; }
I have verify json through JSON Lint and it is saying it is valid JSON string. So why i am getting this errorr?
As your json structure is like below:
{
"success": "yes",
"error": "",
"message": "",
"arguments": [
{
"id": "72820",
"rowNo": "1",
"userId": "40",
"entityId": "3486",
"value": "search Panel",
"typeCategory": "3"
}
]
}
Here you cannot deserialize the arguments array in a string. So you need to redefine the erpAPIResponse class like below using json2csharp utility:
public class erpAPIResponse
{
public string success { get; set; }
public string error { get; set; }
public string message { get; set; }
public List<Argument> arguments { get; set; }
}
public class Argument
{
public string id { get; set; }
public string rowNo { get; set; }
public string userId { get; set; }
public string entityId { get; set; }
public string value { get; set; }
public string typeCategory { get; set; }
}
Now you should have no problem deserializing with your original statements:
response = "{\"success\":\"yes\",\"error\":\"\",\"message\":\"\",\"arguments\":[{\"id\":\"72820\",\"rowNo\":\"1\",\"userId\":\"40\",\"entityId\":\"3486\",\"value\":\"search Panel\",\"typeCategory\":\"3\"}]}";
erpAPIResponse basicResponse = JsonConvert.DeserializeObject<erpAPIResponse>(response);

How to Deserialize Json String with the help of "DataContractJsonSerializer". My Json string has no any name as MainObject

I am unable to deserialize my Json String with the help of "DataContractJsonSerializer". I can't use third party tool for deserialization, my json string has no any enter code hereMainObject so i am unable to do, Please help me. My json data is below.
[{
"id": "2348",
"fo": "",
"na": "og",
"ex": "",
"ge": "",
"no_cl": "Phr",
"wo_cl": {
"id": "27",
"na": "kon",
"na_cl": "WordClass"
},
"con": []
}]
my classes according to above Json is following.
public class WoCl
{
public string id { get; set; }
public string na { get; set; }
public string na_cl { get; set; }
}
public class RootObject
{
public string id { get; set; }
public string fo { get; set; }
public string na { get; set; }
public string ex { get; set; }
public string ge { get; set; }
public string no_cl { get; set; }
public WoCl wo_cl { get; set; }
public List<object> con { get; set; }
}
My deserializing code is following.
string json = returnDictionaryJsonFromServer();//this function returning above json data
List<MainObject> obj = new List<MainObject>();
var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json));
var serializer = new DataContractJsonSerializer(obj.GetType());
obj = serializer.ReadObject(memoryStream) as List<MainObject>;
return obj;
public AllAnnotatedData Deserializer(string json)
{
MyWrapper obj = new MyWrapper();
using (var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
try
{
var serializer = new DataContractJsonSerializer(obj.GetType());
obj = (MyWrapper)serializer.ReadObject(memoryStream);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return obj;
}
//MyWrapper is following.
[DataContract]
public class MyWrapper
{
[DataMember(Name = "objects")]
public List<mySecondWrapper> mySecondWrapper //this is list of my wrapper class.
{ get; set; }
[DataMember(Name = "property1")]
public Meta AllAnnotationMeta
{ get; set; }
[DataMember(Name = "property2")]
public List<myThirdWrapper> myThirdWrapper //this is list of my wrapper class.
{ get; set; }
}

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.