C# - Cannot deserialize the current JSON array - c#

I have this code:
string json2 = vc.Request(model.uri + "?fields=uri,transcode.status", "GET");
var deserial = JsonConvert.DeserializeObject<Dictionary<string, object>>(json2);
var transcode = deserial["transcode"];
var serial = JsonConvert.SerializeObject(transcode);
var deserial2 = JsonConvert.DeserializeObject<Dictionary<string, object>>(serial);
var upstatus = deserial2["status"].ToString();
The json I get from the server is:
{
"uri": "/videos/262240241",
"transcode": {
"status": "in_progress"
}
}
When running it on VS2017, it works.
But on VS2010 I get the following error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'System.Collections.Generic.Dictionary`2[System.String,System.Object]'
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.
I am using Newtonsoft.Json.
Any idea?

Your received json data is not a Dictionary<string, object>, it is a object
public class Transcode
{
public string status { get; set; }
}
public class VModel
{
public string uri { get; set; }
public Transcode transcode { get; set; }
}
You can use this object:
var deserial = JsonConvert.DeserializeObject<VModel>(json2);
instead of:
var deserial = JsonConvert.DeserializeObject<Dictionary<string, object>>(json2);

The best answer was deleted for some reason, so i'll post it:
var deserial = JsonConvert.DeserializeObject<dynamic>(json2);
string upstatus = string.Empty;
upstatus = deserial.transcode.status.ToString();

If your model is not well defined or it is dynamic, then use:
var deserial = JsonConvert.DeserializeObject<dynamic>(json2);
or you can try to use:
JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json2);

Related

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type requires a JSON array (e.g. [1,2,3]) to deserialize correctly

Where I am missing info? I need to deserialize the following JSON string.
{
"data": [
{
"FirstName": "Test",
"LastName": "Test"
}
]
}
For this, I have defined my LoadData Action Method:
public async Task<ActionResult> LoadData()
{
string apiUrl = "URL";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var input = new { depot = "DATA", fromDate = "2020-06-06", toDate = "2020-06-06" };
var response1 = await client.PostAsJsonAsync("DATAOne", input);
if (response1.IsSuccessStatusCode)
{
var data = await response1.Content.ReadAsStringAsync();
var table = JsonConvert.DeserializeObject<List<PartOne>>(data);
}
}
return View();
}
For this, I have defined my class:
public class PartOne
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
}
But when I try using the de-serializer, it gives an exception.
{"Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[InfluxDB.Serie]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo 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.\r\nPath 'results', line 2, position 12."}
You have two options here:
1st Option, you are missing a wrapper object for data
public class Wrapper<T>
{
public T Data { get; set; }
}
and then use:
var table = JsonConvert.DeserializeObject<Wrapper<List<PartOne>>>(json).Data;
2nd Option, deserialize it first as JObject and access to data and then deserialize it to the List<PartOne>:
var jObj = JsonConvert.DeserializeObject(json) as JObject;
var jArr = jObj.GetValue("data");
var table = jArr.ToObject<List<PartOne>>();

Create a JSON object from simple string in C#

I am getting a string as a response from my command line. I want to convert it into a json string , which i will later use to convert to a c# object.
The string Response(sub variable has this string as value)
Access Token 00D0E00000019dU!
Alias accp
Client Id SalesforceDevelopmentExperience
Connected Status Connected
Id 00D
Instance Url https://my.salesforce.com
Username ankur
tried converting it into json by below code
string[] subArray = sub.Split('\n');
string output = JsonConvert.SerializeObject(subArray);
var result = JsonConvert.DeserializeObject<Token>(output);
Token Class
public class Token
{
public string AccessToken { get; set; }
public string Alias { get; set; }
}
It Gives this error
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Token' 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<T> 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
.
Converted JSON
["Access Token 00D0E00000019dU!AQU","Alias accp","Client Id SalesforceDevelopmentExperience","Connected Status Connected","Id 00D","Instance Url https://my.salesforce.com","Username ankur"]
Any Help to convert the string into a JSON/C# object?
It looks far simpler to forget about JSON and parse manually. For example:
//split up the source string into name value pairs
var nameValues = sub.Split('\n')
.Select(s => new
{
Name = s.Substring(0, 18).Trim(),
Value = s.Substring(18).Trim()
});
//Create the token object manually
var token = new Token
{
AccessToken = nameValues.Single(v => v.Name == "Access Token").Value,
Alias = nameValues.Single(v => v.Name == "Alias").Value
};
First of all you should parse this 'sub' string in different way.
Second you should create JObject not trying serialize Array of strings.
Try this
// Splitting into string lines
var subArray = sub.Split('\n')
.Where(x => !string.IsNullOrEmpty(x));
JObject tokenJObj = new JObject();
foreach (var oneSub in subArray)
{
// I assume that the value will be after the last empty character
tokenJObj.Add(
oneSub.Substring(0, oneSub.LastIndexOf(' ')).Trim(),
oneSub.Substring(oneSub.LastIndexOf(' ') + 1));
}
string tokenStringJson1 = tokenJObj.ToString();
// or
string tokenStringJson2 = JsonConvert.SerializeObject(tokenJObj);
Then just add correct attribute on propteries inside your model
public class Token
{
[JsonProperty("Access Token")]
public string AccessToken { get; set; }
// In this property attribute is not requied
[JsonProperty("Alias")]
public string Alias { get; set; }
}

Json response to C# Object

I am trying to convert Json Response to C# object. My code is as below.
$ HttpResponseMessage response = client.GetAsync(TARGETURL).Result;
HttpContent content = response.Content;
// ... Check Status Code
Console.WriteLine("Response StatusCode: " + (int)response.StatusCode);
// ... Read the string.
string result = content.ReadAsStringAsync().Result;
Environment myJsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<Environment>(result);
Console.Write(myJsonResponse.id);
My Json Object Class is:
public class Environment
{
public string id { get; set; }
public string url { get; set; }
public string name { get; set; }
public string error { get; set; }
public int container_hosts_count { get; set; }
}
Result string is:
"[{\"id\":\"23745576\",\"url\":\"https://cloud.mycloud.com/configurations/23745576\",\"name\":\"mycloud Code Screen - Andy Pande\",\"error\":\"\",\"container_hosts_count\":0}]"
I am getting an error as:
Newtonsoft.Json.JsonSerializationException occurred
HResult=0x80131500
Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Environment' 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<T> 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.
As per the error, you are trying to deserialize a JSON array into a single object. Update your deserialization to:
var myJsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<Environment>>(result);

Deserializing an empty array using Json.NET

I've got a C# application that uses Json.NET v7.0.1. As a result of a REST call, I get back some JSON in the form of:
{
"messages": [ {"phoneNumber":"123-456-7890", "smsText":"abcd1234="},
{"phoneNumber":"234-567-8901", "smsText":"efgh5678="},
{"phoneNumber":"345-678-9012", "smsText":"12345asdf"} ]
}
If there is no message data to return, the JSON that I get back looks like this:
{
"messages": [ ]
}
My Message class looks like this:
public class Message
{
public string PhoneNumber { get; set; }
public string SmsText { get; set; }
public Message()
{
}
public Message(string phoneNumber, string smsText)
{
PhoneNumber = phoneNumber;
SmsText = smsText;
}
}
When I try to deserialize the JSON, I'm using the following code:
Message[] messages = JsonConvert.DeserializeObject<Message[]>(json, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Ignore
});
The problem I'm running into is deserializing the JSON when the messages array is empty. When that occurs, I get the following exception:
Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"})
into type 'WindowsFormTestApplication.Message[]' because the type
requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo
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 'messages', line 2, position 15.
When the JSON array is empty, I'd like my Message[] variable to be null. Do I need a custom converter to get this deserialized or am I missing something obvious? Thanks!
You should either send just an array
[ {"phoneNumber":"123-456-7890", "smsText":"abcd1234="},
{"phoneNumber":"234-567-8901", "smsText":"efgh5678="},
{"phoneNumber":"345-678-9012", "smsText":"12345asdf"} ]
Or use some wrapper object like this
public WrapperObject
{
public Message[] messages { get; set; }
}
And then deserialize using it
var wrapper = JsonConvert.DeserializeObject<WrapperObject>(json, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Ignore
});
Create a wrapper class and deserialize the Json into it:
public class MessageArray
{
public Message[] Messages;
}
var messages = JsonConvert.DeserializeObject<MessageArray>(json, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Ignore
});

Cannot deserialize the current JSON object (e.g. {"name":"value"})

This is my JSON data
{
"logInResult": [
{
"Name": "yogesh singh",
"cityName": "",
"img": "DefaultImage/D_Vp_Men.png",
"usrId": "374"
}
]
}
and this is my code
public async Task<ActionResult> Index()
{
HttpClient webClient1 = new HttpClient();
Uri uri = new Uri("http://m.vinipost.com/service/userprofile.svc/logIn?loginId=thyschauhan#gmail.com&pass=12345");
HttpResponseMessage response1;
response1 = await webClient1.GetAsync(uri);
var jsonString = await response1.Content.ReadAsStringAsync();
var _Data = JsonConvert.DeserializeObject<List<JClass>>(jsonString);
foreach (JClass Student in _Data)
{
ViewBag.Message += Student.Name + ", ";
}
dynamic obj = JsonConvert.DeserializeObject(jsonString);
ViewBag.Message += obj.data.Name;
return View();
}
and the error is
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MvcSumit1.Models.JClass]' 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 'logInResult', line 1, position 15.
You can't directly deserialize from your API response using JsonConvert.DeserializeObject.
Try this below code :
JObject jsonResponse = JObject.Parse(jsonString);
JObject objResponse = (JObject)jsonResponse["logInResult"];
Dictionary<string, JArray> _Data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, JArray>>(objResponse.ToString());
Hope this will help you.
You should create the following classes in order to map your json data to actual classes.
public class LogInResult
{
public string Name { get; set; }
public string cityName { get; set; }
public string img { get; set; }
public string usrId { get; set; }
}
public class RootObject
{
public List<LogInResult> logInResult { get; set; }
}
You can then store the RootObject for further processing:
var result = JsonConvert.DeserializeObject<RootObject>(jsonString);
By using the getter for the list, you can get the list and iterate it as usual.
Your question seems to be a duplicate of: Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class
You are trying to deserialize your JSON object into an JSON array.
Store just the content of logInResult into jsonString, that is:
[{"Name":"yogesh singh","cityName":"","img":"DefaultImage\/D_Vp_Men.png","usrId":"374"}]
This of course assumes that you got your JClass correct in the first place.
You're C# code thinks it is reading this:
[
{
"Name": "yogesh singh",
"cityName": "",
"img": "DefaultImage/D_Vp_Men.png",
"usrId": "374"
}
]
i.e. an array of objects, when in fact it is reading an object with a property logInResult, which is an array.
I have faced the same issue, just wanted to point out when there is an array or list exist in JSON like in logInResults is a list of a type, so while deserializing JSON convert is not able to understand that, so what you can do it create your model in this way.
Class giveName
{
givenName[] logInResult {get;set;} // can use list also will work fine
}
public class giveName2
{
public string Name {get;set;}
public string cityName {get;set;}
public string img {get;set;}
public string usrId {get;set;}
}
i will tell you why because see the first curly braces of your json object for that to work, you must have created a type(class) which has a property named logInResult, in the same way object of which the list is made up has to be provided a type and then the properties matching with list items
Note: giveName and giveName2 is the name you can give yourself it wont matter with class name
Convert to collection of object
using Newtonsoft.Json.Linq;
JObject obj = JObject.Parse(jsonString);
JArray arr = (JArray)obj["logInResult"];
IList<JClass> student= arr.ToObject<IList<JClass>>();
return View(student);
Then iterate over it.
IEnumerable<Student>
#foreach (var item in Model)
{
item.Name
item.CityName
item.Img
item.UsrId
}

Categories

Resources