Trying to deserialize JSON using JSON.NET and DataContractJsonSerializer fails - c#

plz help, I'm stuck.
I have a WCF service which returns something like this:
{
"GetDataRESTResult":
[
{"Key1":100.0000,"Key2":1,"Key3":"Min"},
{"Key1":100.0000,"Key2":2,"Key3":"Max"}
]
}
and I would like to deserialize it, but whatever I use (JSON.NET or DataContractJsonSerializer) I'm getting errors.
When using DataContractJsonSerializer I'm using theis code:
byte[] data = Encoding.UTF8.GetBytes(e.Result);
MemoryStream memStream = new MemoryStream(data);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<DataDC>));
List<DataDC> pricinglist = (List<DataDC>)serializer.ReadObject(memStream);
where DataDC is the data contract which I've got from the service reference of the WCF REST service I'm getting the JSON data from, and the error I'm getting is InvalidCastException...
Trying to use JSON.NET I get another exception, but still nothing I can figure out, can anyone help please?
EDIT
Here's a JSON.NET stacktrace:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type
'System.Collections.Generic.List`1[MyApp.MyServiceReference.DataDC]'
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 'GetDataRESTResult', line 1,
position 23.

{"GetDataRESTResult":[{"Key1":100.0000,"Key2":1,"Key3":"Min"},{"Key1":100.0000,"Key2":2,"Key3":"Max"}]}
You data is a JSON object (where it has one key 'GetDataRESTResult' with a JSON array as the value). Because of that, the type you should deserialize into should be an object, not a collection.
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DataDC));
DataDC pricinglist = (DataDC)serializer.ReadObject(memStream);
It will work if your type DataDC look something like this:
public class DataDC
{
public List<Keys> GetDataRESTResult { get; set; }
}
public class Keys
{
public double Key1 { get; set; }
public int Key2 { get; set; }
public string Key3 { get; set; }
}

Below code works
string json = #" {""GetDataRESTResult"":[{""Key1"":100.0000,""Key2"":1,""Key3"":""Min""},{""Key1"":100.0000,""Key2"":2,""Key3"":""Max""}]}";
dynamic dynObj = JsonConvert.DeserializeObject(json);
foreach (var item in dynObj.GetDataRESTResult)
{
Console.WriteLine("{0} {1} {2}", item.Key1, item.Key3, item.Key3);
}
You can also use Linq
var jObj = (JObject)JsonConvert.DeserializeObject(json);
var result = jObj["GetDataRESTResult"]
.Select(item => new
{
Key1 = (double)item["Key1"],
Key2 = (int)item["Key2"],
Key3 = (string)item["Key3"],
})
.ToList();

Related

Json convert array string to object is null

I am having trouble converting my JSON result. I am getting a http response and I am unable to convert it to an object. I have tried changing the Token class into arrays and list types, but no luck. I am using .NET 6.0 Web Api.
Thanks in advance!
public class Tokens
{
public string Token { get; set; }
}
var x = await response.Content.ReadAsStringAsync();
// value of x is "{\"tokens\":[\"6856\",\"d70f1\",\"c66b\",\"45b\",\"3090\",\"8ac68\",\"fsf28\"]}"
var token = JsonConvert.DeserializeObject<Tokens>(x);
// token is null
I have also tried:
var token = JsonConvert.DeserializeObject<List<Tokens>>(x);
But I get the following error:
Error: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[...Tokens]' 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 'tokens', line 1, position 10.
you don't need any custom class, just parse your response
string x = "{\"tokens\":[\"6856\",\"d70f1\",\"c66b\",\"45b\",\"3090\",\"8ac68\",\"fsf28\"]}";
List<string> tokens = JObject.Parse(x)["tokens"].ToObject<List<string>>();
in this case you can acces to each of string separately
var x = tokens[0];
var y = tokens[1];
// etc
or if you need all of them in one string, according to your class
string token = string.Join(",", JObject.Parse(x)["tokens"].ToObject<string[]>());
//result "6856,d70f1,c66b,45b,3090,8ac68,fsf28";
//or more probably
string token = string.Join("", JObject.Parse(x)["tokens"].ToObject<string[]>());
//result "6856d70f1c66b45b30908ac68fsf28";
Your Json string has an array of string, your model only has a string. This is why the deserialisation failing.
Change
public class Tokens
{
public string Token { get; set; }
}
To
public class Tokens
{
public IEnumerable<string> Tokens { get; set; }
}
Or you can deserialise using the following statement
var token = JsonConvert.DeserializeObject<IEnumerable<Tokens>>(x);

To Deserialize JSON and return the Value in C#?

I'm working on Xamarin App, where I'm trying to get the Json data from the server, and it's working fine.
But, now I just want to read/view the value of "invitation".
Json Value:
{"invitation":"http://example.com?c_i=eyJsYWJlbCI6Iklzc3VlciIsImltYWdlVXJsIjpudWxsLCJzZXJ2aWNlRW5kcG9pbnQiOiJodHRwOi8vNTIuNzcuMjI4LjIzNDo3MDAwIiwicm91dGluZ0tleXMiOlsiSE51N0x6MkxoZktONEZEMzM2cWdDNWticWI0dTZWRkt2NERaano4YWc1eHQiXSwicmVjaXBpZW50S2V5cyI6WyI3Sm1MMVhOSHRqSHB2WW1KS3d0ZXM2djltNk5yVUJoZW1ON3J6TnZLcGN0SyJdLCJAaWQiOiIzZjgyNWRkZC0zNjNhLTQ2YzEtYTAxNi0xMjAwY2FhZjRkNTkiLCJAdHlwZSI6ImRpZDpzb3Y6QnpDYnNOWWhNcmpIaXFaRFRVQVNIZztzcGVjL2Nvbm5lY3Rpb25zLzEuMC9pbnZpdGF0aW9uIn0="}
I'm getting this error... don't know why?
Error Message:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Osma.Mobile.App.ViewModels.Index.IndexViewModel+RootObject]' 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<T>) 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 'invitation', line 1, position 14.'
The
Code I wrote.....
Class:
public class ConnectionJson
{
public string Invitation { get; set; }
}
public class RootObject
{
public List<ConnectionJson> ConnectionsJson { get; set; }
}
Main Code :
public async Task<List<RootObject>> ConnectionInvitationJson()
{
HttpClient hTTPClient = new HttpClient();
Uri uri = new Uri(string.Format("http://example.com/Connections/CreateInvitationJson"));
HttpResponseMessage response = await hTTPClient.GetAsync(uri);
string content = await response.Content.ReadAsStringAsync();
var Items = JsonConvert.DeserializeObject<List<RootObject>>(content);
await DialogService.AlertAsync(Items.ToString(), "Connection Invitation Json", "Ok");
return Items;
}
Your Json is just a single object. Update the code as below
var json = JsonConvert.DeserializeObject<ConnectionJson>(content);
After updating the code you can modify the logic as below if you don't want to change the classes structure
var Items = new List<RootObject> { new List<ConnectionJson> { json }};

Able to deserialize string type but not object type

I am using C# with JSON.NET. Below are the two types.
JSON object - var user = { "name": "test", "title": "mytitle"};
JSON String - var user1 = "{ \"name\": \"test\", \"title\": \"mytitle\" }";
Using Newtonsoft.Json to deserialize the JSON object. C# Code in which I am handling JSON.
public class sampledata
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("title")]
public string title { get; set; }
}
public void SampleEvent(string param)
{
sampledata s = JsonConvert.DeserializeObject<sampledata>(param);
}
When I got JSON String in param the deserialization is fine. But when I got JSON object in param - First error I am getting is
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'UCRS.MainWindow+sampledata' because the type requires a JSON object
(e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g.
{"name":"value"}) or change the deserialized type to an array or a
type that implements a collection interface (e.g. ICollection, IList)
like List that can be deserialized from a JSON array.
JsonArrayAttribute can also be added to the type to force it to
deserialize from a JSON array.
Path '', line 1, position 1.
So I changed the code as :
List<sampledata> s = JsonConvert.DeserializeObject<List<sampledata>>(param);
Then I am facing different issue
" Unexpected character encountered while parsing value: o. Path '',
line 1, position 1."
When some event is raised in web page I am handling that event in c# using webbrowser objectforscripting. I always get the JSON object as param. How to deserialize JSON object in C#? Please help
Its pretty simple..working for both
string jsonObject = #"{""name"":""test"",""title"":""mytitle""}";
var jsonString = "{ \"name\": \"test\", \"title\": \"mytitle\" }";
var values1 = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonObject);
var values2 = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
This is also working
var values3 = JsonConvert.DeserializeObject<sampledata>(jsonObject);
I created JObject
JObject jObject = new JObject
{
{"name", "test" },
{"title", "mytitle" }
};
string jObjectStr = jObject.ToString();
var values = JsonConvert.DeserializeObject<sampledata>(jObjectStr);
The updated line of code:
List<sampledata> s = JsonConvert.DeserializeObject<List<sampledata>>(param);
is perfectly fine.
The problem here is that the deserializer is expecting an array when you are trying to deserialize to a list.
Try making it an array. Add this line of code to the param string:
param ="["+param+"]";//make it an array before deserialization
Complete code:
public class sampledata
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("title")]
public string title { get; set; }
}
public void SampleEvent(string param)
{
param ="["+param+"]";//make it an array before deserialization
List<sampledata> s = JsonConvert.DeserializeObject<List<sampledata>>(param);
}

Convert an FeedResponse<Class> into List<Class> in DocumentDB

I'm trying to convert a FeedResponse into List but failing to serialize the string as it throws an error
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Lutran.Api.Models.Infinity]' 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 'token', line 1, position 9.
I have used the logic for pagination using the this link and getting the data when returning the entire output object but when im trying to convert it fails.Tried using an ienumerable object but it shows type conversion error.Used a dynamic object but cannot extract ResponseContinuation value from it.
Using Newton Soft to convert the json(deserialize the string)
var query = client.CreateDocumentQuery<Document>(collection, options).AsDocumentQuery();
if (query.HasMoreResults)
{
var result = await query.ExecuteNextAsync<LeadDataView>();
objLeadDataView.ResponseContinuation = result.ResponseContinuation;
objLeadDataView.InfinityDataView = JsonConvert.DeserializeObject<List<Infinity>>(result.ToString());
response = objLeadDataView;
}
I Figured it out
public class LeadDataView
{
public string ResponseContinuation { get; set; }
public FeedResponse<Infinity> InfinityDataView { get; set; }
}
if (query.HasMoreResults)
{
var result = await query.ExecuteNextAsync<Infinity>();
objLeadDataView.ResponseContinuation = result.ResponseContinuation;
objLeadDataView.InfinityDataView = result;
response = objLeadDataView;
}
So the above code sent the continuation token on top and infinity class data below.enter image description here

Deserialize json array using RestSharp and JSON.Net in C# ASP.NET

I am having an issue I have been researching and can not seem to figure out. I am trying to deserialize Json return from a restsharp call to an api. It worked great on my first one where there was not an array involved. Now that I am trying to do it on a string with an array in it I am having issues. If anybody could help me figure this out it would be greatly appreciated, thank you in advance.
So I am trying to get Roles to be stored to my Model, but it fails because it is an array:
Here is my method:
var request = new RestRequest("api/user/{id}", Method.GET);
request.AddUrlSegment("id", id);
var response = client.Execute(request) as RestResponse;
var d = JsonConvert.DeserializeObject<List<MyModel>>(response.Content);
The error I am getting is on the above line at var d = .... It says:
Cannot implicitly convert type
'System.Collections.Generic.List<Models.MyModel>' to 'Models.MyModel'
The response for var response is (trying to get Roles stored in d to store in model):
"{\"Id\":22,\"FirstName\":\"Shawn\",\"LastName\":\"John\",\"Roles\":[\"User\"]}"
My MyModel looks like so:
public class MyModel
{
public string Id { get; set; }
public string Roles { get; set; }
}
Updated code
Getting this error now on the same line:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[Models.MyModel]' 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<T>) 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.
Changed model to be :
public List<MyModel> Roles { get; set; }
and controller variable to :
List<MyModel> deSerialize2 =
JsonConvert.DeserializeObject<List<MyModel>>(response.Content);
try changing your model to
public class MyModel
{
public int Id { get; set; }
public List<string> Roles { get; set; }
}
Roles is an array of strings.
Edit: After further inspection, id is actually an integer not a string.
Also, change your deserialize call to this
var d = JsonConvert.DeserializeObject<MyModel>(response.Content);
The json response isn't an array.

Categories