Need to de-serialize an array of array response to List<Model>
This is my response from other endpoint:
"[[{"BillRateCardId":6992,"ExternalRateCardId":"cd77d9b5-a00e-4696"}]]"
Am using the below line of code to deserialize it to the Model but receiving the error "cant de-serialize that":
List<Model> Res = JsonConvert.DeserializeObject<List<Model>>(Response);
You need to specify the data type that List is expected to contain, either by modeling it as an object:
using Newtonsoft.Json;
var input = "[[{\"BillRateCardId\":6992,\"ExternalRateCardId\":\"cd77d9b5-a00e-4696\"}]]";
var deserialized = JsonConvert.DeserializeObject<List<List<ResponseModel>>>(input);
class ResponseModel
{
public int BillRateCardId { get; set; }
public string? ExternalRateCardId { get; set; }
}
or by using dynamic, but then you lose static type checking:
using Newtonsoft.Json;
var input = "[[{\"BillRateCardId\":6992,\"ExternalRateCardId\":\"cd77d9b5-a00e-4696\"}]]";
var deserialized = JsonConvert.DeserializeObject<List<List<dynamic>>>(input);
Console.WriteLine(JsonConvert.SerializeObject(deserialized));
since you have only one value, you don't need the custom class
var data = JArray.Parse(Response);
long billRateCardId = data.SelectMany(x=>x)
.Where(x =>(string) x["ExternalRateCardId"]=="cd77d9b5-a00e-4696")
.Select(x=>(long) x["BillRateCardId"]).FirstOrDefault();
Related
I have model as below:
public class CustomModel
{
public string Data1 { get; set; }
public string Data2 { get; set; }
}
public class root
{
public List<CustomModel> data { get; set; }
}
My payload is as below:
List<CustomModel> cms = new List<CustomModel>();
CustomModel cm1 = new CustomModel();
cm1.Data1 = "a";
cm1.Data2 = "b";
cms.Add(cm1);
CustomModel cm2 = new CustomModel();
cm2.Data1 = "D";
cm2.Data2 = "E";
cms.Add(cm2);
BaseClass baseClass = new BaseClass();
baseClass.data = cms;
My JSON is:
var json = new JavaScriptSerializer().Serialize(baseClass);
And Result is:
{"data":[{"data1":"a","data2":"b"},{"data1":"D","data2":"E"}]}
BUT I need: without the "data" property as below:
{[{"data1":"a","data2":"b"},{"data1":"D","data2":"E"}]}
I tried the below function:
public static IEnumerable<object> GetPropertyValues<T>(T input)
{
return input.GetType()
.GetProperties()
.Select(p => p.GetValue(input));
}
Like
var value_only = GetPropertyValues(baseClass);
var json = new JavaScriptSerializer().Serialize(value_only);
BUT it returns [[{"data1":"a","data2":"b"},{"data1":"D","data2":"E"}]]
Is there anywasy to do it other than manually adding? Please help.
Note that {[{"data1":"a","data2":"b"},{"data1":"D","data2":"E"}]} is not valid json. In Json objects, data/values are organized by (named) properties.
However, here you seem to want a (root) Json object containing a value being Json array, but that value is not associated with a Json object property, thus not being valid Json.
If you really want invalid Json, i suggest you serialize the List<CustomModel> instance instead of the root model instance, resulting in a Json array, and then manually adding the surrounding { and } to the serialized Json string, thus giving you your desired invalid Json result:
var json = new JavaScriptSerializer().Serialize(baseClass.data);
var desiredResult = "{" + json + "}";
you don't need root class (or base class you must to deside what is name. Just use
var json = new JavaScriptSerializer().Serialize(cms);
PS.
And it is time to select a modern serializer.
I have this json string, which contains two elements each with a Number and a Status:
var jsonString = "{\"Errors\":[{\"Number\":9,\"Status\":\"BadRequest\"}, {\"Number\":3,\"Status\":\"BadConnection\"}]}";
As you see it has a parent property called Errors.
I have prepared this model:
public class ExceptionStructure
{
public int Number { get; set; }
public string Status { get; set; }
}
Using NewtonSoft.Json I would like to deserialize the json string into an array of ExceptionStructure objects, without also having to create a model for the parent property (as I don't really need it).
Can I do this (perhaps with some json attribute on the model class)?
I was hoping to do something like this to deserialize:
var exceptionArr = JsonConvert.DeserializeObject<ExceptionStructure>(jsonString);
JSON.NET allows you to deserialize parts of a json file. You can do this by first deserialzing the json string to a JObject, extract the relevant parts, and then deserialize those to your actual object.
JObject errors = JObject.Parse(jsonString);
IList<JToken> results = errors["Errors"].Children().ToList();
IList<ExceptionStructure> exceptions = new List<ExceptionStructure>();
foreach (JToken result in results)
{
ExceptionStructure exception= result.ToObject<ExceptionStructure>();
exceptions.Add(exception);
}
Honestly though, in your case it might be easier to just build a Errors parent class
More information can be found at http://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm
this is may be helpful you.
string s = "{\"Errors\":[{\"Number\":9,\"Status\":\"BadRequest\"}, {\"Number\":3,\"Status\":\"BadConnection\"}]}";
var jobj = JObject.Parse(s);
List<ExceptionStructure> list = jobj["Errors"].ToObject<List<ExceptionStructure>>();
OR:
string s = "{\"Errors\":[{\"Number\":9,\"Status\":\"BadRequest\"}, {\"Number\":3,\"Status\":\"BadConnection\"}]}";
List<ExceptionStructure> list = JObject.Parse(s)
.SelectToken("Errors")
.ToObject<List<ExceptionStructure>>();
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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Facebook;
using Newtonsoft.Json;
namespace facebook
{
class Program
{
static void Main(string[] args)
{
var client = new FacebookClient(acc_ess);
dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"});
string jsonstring = JsonConvert.SerializeObject(result);
//jsonstring {"data":[{"target_id":9503123,"target_type":"user"}]}
List<RootObject> datalist = JsonConvert.DeserializeObject<List<RootObject>>(jsonstring);
}
public class Datum
{
public Int64 target_id { get; set; }
public string target_type { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
}
}
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type
'System.Collections.Generic.List`1[facebook.Program+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) that can be
I looked at other posts.
My json looks like this:
{"data":[{"target_id":9503123,"target_type":"user"}]}
To make it clear, in addition to #SLaks' answer, that meant you need to change this line :
List<RootObject> datalist = JsonConvert.DeserializeObject<List<RootObject>>(jsonstring);
to something like this :
RootObject datalist = JsonConvert.DeserializeObject<RootObject>(jsonstring);
As the error message is trying very hard to tell you, you can't deserialize a single object into a collection (List<>).
You want to deserialize into a single RootObject.
Can you try to change your json without data key like below?
[{"target_id":9503123,"target_type":"user"}]
That happened to me too, because I was trying to get an IEnumerable but the response had a single value. Please try to make sure it's a list of data in your response. The lines I used (for api url get) to solve the problem are like these:
HttpResponseMessage response = await client.GetAsync("api/yourUrl");
if (response.IsSuccessStatusCode)
{
IEnumerable<RootObject> rootObjects =
awaitresponse.Content.ReadAsAsync<IEnumerable<RootObject>>();
foreach (var rootObject in rootObjects)
{
Console.WriteLine(
"{0}\t${1}\t{2}",
rootObject.Data1, rootObject.Data2, rootObject.Data3);
}
Console.ReadLine();
}
Hope It helps.
The real problem is that you are using dynamic return type in the FacebookClient Get method. And although you use a method for serializing, the JSON converter cannot deserialize this Object after that.
Use insted of:
dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"});
string jsonstring = JsonConvert.SerializeObject(result);
something like that:
string result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"}).ToString();
Then you can use DeserializeObject method:
var datalist = JsonConvert.DeserializeObject<List<RootObject>>(result);
Hope this helps.
public partial class tree
{
public int id { get; set; }
public string name { get; set; }
public string sciencename { get; set; }
public int familyid { get; set; }
}
private async void PopulateDataGridView()
{
//For Single object response
tree treeobj = new tree();
treeobj = JsonConvert.DeserializeObject<tree>(Response);
//For list of object response
List<tree> treelistobj = new List<tree>();
treelistobj = JsonConvert.DeserializeObject<List<tree>>(Response);
//done
}
I've got a JSON data from Twitter API SEARCH.
I'm trying to deserialize these data into objects.
The JSON scheme looks like this:
{
"element": INT,
"element2": STRING,
..
..
"Results":[
{
"user":STRING,
"image":STRING,
..
..
}
]
}
How could I deserialize those JSON elements into objects using JSON Toolkit or something else?
Create a class that matches the JSON schema
public class Data
{
public string Element{get;set;}
public string Element2{get;set;}
public List<Result> Results{get;set;}
}
public class Result
{
public string User{get;set;}
public string Image{get;set;}
}
and use JSON.NET to deserialize
var result = JsonConvert.DeserializeObject<Result>(json);
If you have problems with correct type definition, you can always use dynamic deserialization using Json.Net:
var original = JsonConvert.DeserializeObject<dynamic>(jsonstring);
and then build your desired object based on it (if for example the original one contains overhead information set, and you don't need all of them):
var somepart = new {
E1 = original.element1,
E2 = original.element2
};