why I cant deserlize json using datacontractserializer when using wrapped format - json

My wcf service uses the wrapped format body style. When I try deserializing it using DataContractJsonSerializer isn't deserializing the json properly
SignInResult returnedUser = new SignInResult();
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(provider.SignIn(username, password)));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SignInResult),"root");
returnedUser = serializer.ReadObject(stream) as SignInResult;
stream.Close();
return returnedUser;
but I don't get a object populated according to the following json
{
"SignInResult": {
"CreationDate": "/Date(1480598102923+0000)/",
"Email": "bladsa#as.com",
"IsApproved": true,
"IsLockedOut": false,
"IsOnline": true,
"IsValidLogin": true,
"LastActivityDate": "/Date(1490954750307+0100)/",
"LastLockoutDate": "/Date(-6816268800000+0000)/",
"LastLoginDate": "/Date(1490954750307+0100)/",
"LastPasswordChangedDate": "/Date(-2208988800000+0000)/",
"ProviderName": "LoginProvider",
"ProviderUserKey": "dcc5f38f-f71e-4d9d-bdb2-58fb60b7a65e",
"UserName": "schoi"
}
}
It does work if I use the bare format so it definately something to do with the wrapped message format.
I know I can do this in Newsoft json but I know I will get asked to use Microsofts way.

its so simple. at first we create a jsondeserilzer method like this:
public static T DataJsonDeserializer<T>(string jsonString)
{
var mStrm = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
var jsonSerializer = new DataContractJsonSerializer(typeof(T));
var objResponse = jsonSerializer.ReadObject(mStrm);
return (T)objResponse;
}
then we create a json object like this:
public class SignInResult
{
public DateTime CreationDate { get; set; }
public string Email { get; set; }
public bool IsApproved { get; set; }
public bool IsLockedOut { get; set; }
public bool IsOnline { get; set; }
public bool IsValidLogin { get; set; }
public DateTime LastActivityDate { get; set; }
public DateTime LastLockoutDate { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime LastPasswordChangedDate { get; set; }
public string ProviderName { get; set; }
public string ProviderUserKey { get; set; }
public string UserName { get; set; }
}
public class RootObject
{
public SignInResult SignInResult { get; set; }
}
finally you can deserilze any thing like this:
var x = JsonDeserializer<RootObject>(provider.SignIn(username, password)));

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

json parse from combobox data

want to parse a JSON string in combobox to 'text'. The response is something like
How can I parse the JSON and extract its 'text' values?
var restClient = new RestClient("https://cbsservis.tkgm.gov.tr/megsiswebapi.v2/api/idariYapi/ilListe");
var restRequest = new RestRequest(Method.GET);
var restResponse = restClient.Execute(restRequest);
restRequest.AddHeader("Accept", "text/json");
var jArray = Newtonsoft.Json.Linq.JObject.Parse(restResponse.Content);
dynamic jsonResponse = JsonConvert.DeserializeObject(restResponse.Content);
dynamic jsonResponse2 = JsonConvert.DeserializeObject<RootObject>(string JObject);`
Your response can be represented by classes like this:
public class Rootobject
{
public Feature[] features { get; set; }
public string type { get; set; }
public Crs crs { get; set; }
}
public class Crs
{
public string type { get; set; }
public Properties properties { get; set; }
}
public class Properties
{
public string name { get; set; }
}
public class Feature
{
public string type { get; set; }
public Geometry geometry { get; set; }
public Properties1 properties { get; set; }
}
public class Geometry
{
public string type { get; set; }
public object[][][] coordinates { get; set; }
}
public class Properties1
{
public string text { get; set; }
public int id { get; set; }
}
Hence your code can be changed to:
var restClient = new RestClient("https://cbsservis.tkgm.gov.tr/megsiswebapi.v2/api/idariYapi/ilListe");
var restRequest = new RestRequest(Method.GET);
var restResponse = restClient.Execute(restRequest);
restRequest.AddHeader("Accept", "text/json");
var obj = JsonConvert.DeserializeObject<Rootobject>(restResponse.Content);
You will receive the object like this:
And then you can loop through properties to get desired text.

Extracting JSON data using Newtonsoft in xamarin.android

Hello I am getting JSON data from server and i want to extract that JSON in Xamarin. How can i parse that JSON using NewTonSoft
below is the JSON responce i receive
[
{
"Id": 5,
"AlbumKey": "2REC2ZDSFK",
"ZipFillPath": "aaaa#gmail.com\\2REC2ZDSFK",
"NoOfPages": 3,
"EmailID": "aaaa#gmail.com"
}
]
This should be your Model
public class RootObject
{
public int Id { get; set; }
public string AlbumKey { get; set; }
public string ZipFillPath { get; set; }
public int NoOfPages { get; set; }
public string EmailID { get; set; }
}
Then
RootObject myObj = JsonConvert.DeserializeObject<RootObject>(json);
If your json is a List of objects, something like
List<RootObject> myListObj = JsonConvert.DeserializeObject<List<RootObject>>(json);
public class yourClass
{
public int Id { get; set; }
public string AlbumKey { get; set; }
public string ZipFillPath { get; set; }
public int NoOfPages { get; set; }
public string EmailID { get; set; }
}
Considering this as your model class you can
var responseText= JsonConvert.DeserializeObject<yourClass>(jsonResponse);
Then depending on if its a list or a not you can get the data from it
In case you are unable to find the class what you can do is check if the namespace of your current class and that class is the same.

Deserialize OneNote Notebooks API Response

I'm getting an empty object when I try to Deserialize a OneNote GetAllNotebooks query.
string[] tempCapture = null;
var url = new Uri("https://graph.microsoft.com/v1.0/me/onenote/notebooks");
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}
var response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
tbResponse.Text = result.ToString();
DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<Value>));
MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(tbResponse.Text.ToString()));
var obj1 = (List<Value>)ser1.ReadObject(stream1);
I'm trying to get a list of notebooks, names, links to add to a database. And my table structure matches the class below.
Here is my OneNote API class
public class Value
{
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
public string name { get; set; }
public string self { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public string id { get; set; }
public string createdTime { get; set; }
}
Here is my new code with the RootObject. I'm still getting an error. It is in the catch exception.
var test = await client.GetAsync(url);
string testStr = await test.Content.ReadAsStringAsync();
DataContractJsonSerializer serial = new DataContractJsonSerializer(typeof(RootObject));
MemoryStream testStream = new MemoryStream(Encoding.UTF8.GetBytes(testStr));
try
{
var objx = (List<RootObject>)serial.ReadObject(testStream);
}
catch(Exception ex)
{
ex.ToString();
//"There was an error deserializing the object of type OneNoteSOAP2.RootObject. End element 'createdBy' from namespace '' expected. Found element 'user' from namespace ''."
}
You can use http://json2csharp.com/. Basically, just copy the value of our JSON being returned, and use the classes generated by this website. Use RootObject to deserialize.
I ran this for you and obtained these classes:
public class OneNoteClientUrl
{
public string href { get; set; }
}
public class OneNoteWebUrl
{
public string href { get; set; }
}
public class Links
{
public OneNoteClientUrl oneNoteClientUrl { get; set; }
public OneNoteWebUrl oneNoteWebUrl { get; set; }
}
public class Value
{
public string id { get; set; }
public string self { get; set; }
public string createdTime { get; set; }
public string name { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
}
public class RootObject
{
public List<Value> value { get; set; }
}

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; }
}