I am getting error while deserializing jsonString.
Error is Type 'oodleListingsUser' is not supported for deserialization of an array.
My code of deserialization is
string jsonString = new WebClient().DownloadString("http://api.oodle.com/api/v2/listings?key=TEST®ion=region_value&category=category_value&format=json");
JavaScriptSerializer ser = new JavaScriptSerializer();
jsonOodleApi p = ser.Deserialize<jsonOodleApi>(jsonString);
My class defination of jsonOodleApi is
public class jsonOodleApi
{
public oodleCurrent current;
public oodleListings[] listings;
public oodleMeta meta;
public string state { get; set; }
}
Defination of oodleCurrent and oodleMeta I am not giving because its perfect !
Defination of oodleListings is
public class oodleListings
{
public string id { get; set; }
public string title { get; set; }
public oodleListingsUser user;
// I have skipped some of fields because it have no issue at all.
}
Defination of oodleListingsUser is
public class oodleListingsUser
{
public string id { get; set; }
public string url { get; set; }
public string name { get; set; }
public string photo { get; set; }
}
The problem is my jsonString sometimes returns only one value of user (type of oodleListingsUser), and sometimes it returns array of user, and sometimes it returns null of user !
When it returns only one user, it runs perfectly fine ! No issue.
But when it returns array of user, bloom ! error occurs Type 'oodleListingsUser' is not supported for deserialization of an array.
Even I have tried public oodleListingsUser[] user But it gives error as
No parameterless constructor defined for type of 'oodleListingsUser[]'
for the value which returns only one user !
Now what should i do to solve this issue ?
Try:
public oodleListings[] listings = new oodleListings[0];
Or make it a List<oodleListings> perhaps.
Related
I have a Json file in the following format:
"Adorable Kitten": {"layout": "normal","name": "Adorable Kitten","manaCost": "{W}","cmc": 1,"colors": ["White"],"type": "Host Creature — Cat","types": ["Host","Creature"],"subtypes": ["Cat"],"text": "When this creature enters the battlefield, roll a six-sided die. You gain life equal to the result.","power": "1","toughness": "1","imageName": "adorable kitten","colorIdentity": ["W"]}
and I am using the following code to put it into a list:
using (StreamReader r = new StreamReader(filepath))
{
string json = r.ReadToEnd();
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
textBox1.Text = items[0].name.ToString();
}
public class Item
{
public string layout;
public string name;
public string manaCost;
public string cmc;
public string[] colors;
public string type;
public string[] types;
public string[] subtypes;
public string text;
public string power;
public string toughness;
public string imageName;
public string[] colorIdentity;
}
Visual Studio is telling me that the "Adorable Kitten" part of the Json can not be deserialized. Normally I would get rid of that portion of the code but it is an excerpt from a file that is nearly 40000 lines long, so removing that for each item would be impractical. Additionally when i removed "Adorable Kitten" while troubleshooting I got a similar error for "layout". The error says that i need to either put it into a Json array or change the deserialized Type so that it is a normal .Net Type. Can anyone point what I'm doing wrong?
If your example is really what you are doing then you're simply deserializing to the wrong type.
Right now your code would work for the following:
[{"layout": "normal","name": "Adorable Kitten","manaCost": "{W}","cmc": 1,"colors": ["White"],"type": "Host Creature — Cat","types": ["Host","Creature"],"subtypes": ["Cat"],"text": "When this creature enters the battlefield, roll a six-sided die. You gain life equal to the result.","power": "1","toughness": "1","imageName": "adorable kitten","colorIdentity": ["W"]}]
Notice that it is a single JSON object inside a JSON array. This corresponds to the type you are deserializing to (List<Item>).
The example you posted of your JSON file isn't valid JSON (unless there are curly braces around the whole thing you left out) so you need to fix the file. If you really want there to be a list of Items in the JSON then wrapping everything in a single array will be the correct way to represent that.
First check if that the JSON you're receiving is a valid JSON, apparently the one you're receiving is wrong, you can check in https://jsonlint.com
Second create a model for the JSON, you can do it here http://json2csharp.com
public class AdorableKitten
{
public string layout { get; set; }
public string name { get; set; }
public string manaCost { get; set; }
public int cmc { get; set; }
public List<string> colors { get; set; }
public string type { get; set; }
public List<string> types { get; set; }
public List<string> subtypes { get; set; }
public string text { get; set; }
public string power { get; set; }
public string toughness { get; set; }
public string imageName { get; set; }
public List<string> colorIdentity { get; set;
}
}
Don't forget about the getters and setters on your model.
I have this json:
[{"trace":{"details":{"date":"[28-02-2016 11:04:26.856573]","type":"[info]","message":"[system done.]"},"context":{"context":[[{"ID":"john dillinger"}]]}}},{"trace":{"details":{"date":"[28-02-2016 11:04:26.856728]","type":"[info]","message":"[trace done.]"},"context":{"context":[[{"ID":"john dillinger"}]]}}}]
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type, because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
I've created this class for deserialize it:
public class Testing
{
public string date { get; set; }
public string type { get; set; }
public string message { get; set; }
public string context { get; set; }
}
and this is the code for deserialize the content:
string responseText = "json above";
var obj = JsonConvert.DeserializeObject<Testing>(responseText); //on this line the problem
in the obj line I get the exception. I'm a bit rusty with c# so I don't know exactly what am I doing wrong. Someone could enlighten me?
Your json is not a flat data as your Testing class is. Try using following
public class Details
{
public string date { get; set; }
public string type { get; set; }
public string message { get; set; }
}
public class Context
{
public List<List<ContextElement>> context { get; set; }
}
public class Trace
{
public Details details { get; set; }
public Context context { get; set; }
}
public class RootObject
{
public Trace trace { get; set; }
}
Just hit your json to http://json2csharp.com/ and it seems you need to add this type for the ID part of the context and modify the result so context uses this in the list.
public class ContextElement
{
public string ID { get; set; }
}
Your parsed json is of format
Check this with https://jsonformatter.curiousconcept.com/ yourself. Then you just need to make a C# classes to match that structure.
You need to deserialize a collection of Trace - like List<Trace>:
var obj = JsonConvert.DeserializeObject<List<Trace>>(responseText);
Assuming that you have the following DTOs:
public class Trace
{
public TraceValue trace;
}
public class TraceValue
{
public Details details;
public Context context;
}
public class Details
{
public String date;
public String type;
public String message;
}
public class Context
{
public List<List<IdItem>> context;
}
public class IdItem
{
public String ID;
}
Proof (response is just a line provided by you, but with escaped quotes, so that it can be put directly into the code):
var response =
"[{ \"trace\":{ \"details\":{ \"date\":\"[28-02-2016 11:04:26.856573]\",\"type\":\"[info]\",\"message\":\"[system done.]\"},\"context\":{ \"context\":[[{\"ID\":\"john dillinger\"}]]}}},{\"trace\":{\"details\":{\"date\":\"[28-02-2016 11:04:26.856728]\",\"type\":\"[info]\",\"message\":\"[trace done.]\"},\"context\":{\"context\":[[{\"ID\":\"john dillinger\"}]]}}}]";
var obj = JsonConvert.DeserializeObject<List<Trace>>(response);
I think you should use JavaScripSerializer
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
you can try
var obj = jsSerializer.Deserialize<Testing>(responseText);
I am not sure about this solution, may be it will work or not in your case.
But you can deserialize json string into string array of any dimension as:
var obj = jsSerializer.Deserialize<string[]>(responseText);
var obj = jsSerializer.Deserialize<string[][]>(responseText);
I sent the following JSON to a WCF service which accepts Stream as a parameter.
{"ReservationStream":
{"clientFirstName":"Abe",
"clientLastName":"Lincoln",
"clientPhone":"0544944860",
"clientEmail":"abe#mail.com",
"pickupLocationID":"3699",
"pickupAddressString":"JFK Airport Terminal 1",
"pickupFlightNumber":"LY001",
"pickupAirline":"El Al",
"pickupAirportName":"John F Kennedy Intl",
}
}
In the debugger, the stream variable shows all values as expected. I want to deserialize into a class defined as follows:
public class ReservationStream
{
public String clientFirstName { get; set; }
public String clientLastName { get; set; }
public String clientPhone { get; set; }
public String clientEmail { get; set; }
public String pickupLocationID { get; set; }
public String pickupAddressString { get; set; }
public String pickupFlightNumber { get; set; }
public String pickupAirline { get; set; }
public String pickupAirportName { get; set; }
}
When I call
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
ReservationStream structuredReservations = javaScriptSerializer.Deserialize<ReservationStream>(strJSON);
no exception is thrown, but all of the fields have null values. Where is my mistake?
I think it's because your JSON object is nested inside a ReservationStream tag.
Try with just:
{
"clientFirstName":"Abe",
"clientLastName":"Lincoln",
"clientPhone":"0544944860",
"clientEmail":"abe#mail.com",
"pickupLocationID":"3699",
"pickupAddressString":"JFK Airport Terminal 1",
"pickupFlightNumber":"LY001",
"pickupAirline":"El Al",
"pickupAirportName":"John F Kennedy Intl"
}
You're trying to deserialize an object containing a ReservationStream object rather than the ReservationStream object itself.
One way to get around this is to make a wrapper class which contains a ReservationStream and deserialize using this:
public class WrapperClass
{
public ReservationStream ReservationStream { get; set; }
}
WrapperClass wrapperClass = serializer.Deserialize<WrapperClass>(strJSON);
I once have the same problem and I removed the javaScriptSerializer and directly used the method parameter like this
public static string UpdateTemplateProperties(TemplateProperties templateProperties)
{
var x = templateProperties.Something
}
and I have the javascript object structure as you
just be sure to have the same name for the parameter and the first object-name in your javascript object literal
Couldn't find an answer from the other Json Serialization issue questions, so maybe someone can help me:
I'm getting a JSON object from a REST api and attempting to Deserialize it to an object. Below is the JSON Object I receive:
{"id":"6wVcZ9ZF67ECUQ8xuIjFT2",
"userId":"83ca0ab5-3b7c-48fe-8019-000320081b00",
"authorizations":["employee","API","trainer","queueAdmin","supervisor","workflowAdmin","realtimeManager","forecastAnalyst","qualityEvaluator","contactCenterManager","teamLead","personnelAdmin","telephonyAdmin","qualityAdmin","businessAdmin","businessUser","accountAdmin","dialerAdmin","contentManagementUser","contentManagementAdmin","admin","api","scriptDesigner","agent","user"],
"primaryAuthorization":"employee",
"thirdPartyOrgName":"in",
"username":"somebody",
"selfUri":"https://blahblahblah.com/api/v1/auth/sessions/6wVcZ9ZF67ECUQ8xuIjFT2"}
And my object I'm attempting to DeSerialize to:
[Serializable]
public class Session : BaseRequest, ISession
{
public Session(string url) : base(url)
{
}
#region Members
[JsonProperty(PropertyName = "userId")]
public string UserId { get; set; }
[JsonProperty(PropertyName = "authorizations")]
public object[] Authorizations { get; set; }
[JsonProperty(PropertyName = "primaryAuthorization")]
public string PrimaryAuthorization { get; set; }
[JsonProperty(PropertyName = "thirdPartyOrgName")]
public string ThirdPartyOrgName { get; set; }
[JsonProperty(PropertyName = "username")]
public string Username { get; set; }
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "selfUri")]
public string SelfUri { get; set; }
#endregion
}
I simply make the web request and get the response stream using a stream reader and return the string. Pretty standard.
However, when I attempt to Deserialize into my Session object it always throws an error: Value Cannot be Null
var serializer = new JsonSerializer();
response = MakePostRequest(true);
var obj = serializer.Deserialize<Session>(new JsonTextReader(new StringReader(response)));
The response is the JSON string I get back from the web request and is exact to what I specified above.
I've done this before but normally I've been the one that designed the REST api. Not the case this time but I can't for the life of my figure out why this won't deserialize? I've specified the JSonProperty PropertyName to avoid issues with proper casing, is this not working right maybe? Any help is appreciated!
UDPATE
I think I found part of the problem. It is attempting to deserialize my base class which consists of :
public abstract class BaseRequest
{
protected BaseRequest(string apiUrl)
{
ApiUrl = apiUrl;
Request = (HttpWebRequest)WebRequest.Create(apiUrl);
}
public string ApiUrl { get; set; }
public string JsonPayload { get; set; }
public HttpWebRequest Request { get; private set; }
}
Is there any directive I can give to prevent it from doing so? Or will I need to refactor around this?
Below code works (using Json.Net):
var session = JsonConvert.DeserializeObject<Session>(json);
public class Session
{
public string Id { get; set; }
public string UserId { get; set; }
public List<string> Authorizations { get; set; }
public string PrimaryAuthorization { get; set; }
public string ThirdPartyOrgName { get; set; }
public string Username { get; set; }
public string SelfUri { get; set; }
}
EDIT
How should I tell it to ignore the base class?
var session = (Session)System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject(typeof(Session));
JsonConvert.PopulateObject(DATA, session);
But I don't think this is a nice way of doing it. Changing your design may be a better solution.
I've tested your code and it works fine, only change I made was removing the constructor, I take it that the serializer can't create an instance on the object for some reason, can you remove
public Session(string url) : base(url)
{
}
Your code works just fine for me but I haven't the BaseRequest source code so I made class with empty constructor.
IMO the exception is coming exactly from there. In the Session constructor the url parameter is null because your JSON object doesn't have url property. May be in the BaseRequest class you use this url param and you receive the Value Can't be Null error.
You can change just the name of parameter if this is the issue:
public Session(string selfUri ) : base(selfUri)
{
}
Check also if the 'response' variable is null. StringReader can throw this exception if you pass null to its constructor.
i am getting a list of pagepack assistant by calling a webservice. I have added the web reference.
using org.xerox.xde3.na.sdi.amiller_v_vista;
public org.xerox.xde3.na.sdi.amiller_v_vista.DDCControl proxy;
in page load method i am calling the web method as follows
proxy = new DDCControl();
Guid y = new Guid("45a5b1c2-2fa5-4136-abdd-bc213b694848");
DataList1.DataSource = proxy.GetAllDDCs(this.AccountID, y);
DataList1.DataBind();
I am getting the following error:
An invalid data source is being used for DataList1. A valid data source must implement either IListSource or IEnumerable
public DDCReturnGetAll GetAllDDCs(Guid accountId, Guid authToken);
the return type of GetAllDDCs is DDCReturnGetAll
where
public class DDCReturnGetAll : DDCReturnBase
{ public DDCReturnGetAll();
public DDCInfo2[] DDCs { get; set; } }
where
DDCInfo2 is
public class DDCInfo2 { public DDCInfo2();
public BrandingType brandingType { get; set; }
public string ChargebackName { get; set; }
public string CollectorName { get; set; }
public string Description { get; set; }
public string URL { get; set; } }
Can you please help me with this issue?
The object returned from GetAllDDCs doesn't implement IListSource or IEnumerable. Most likely the object returned has a property on it that you should bind to instead.
You will need to look at the return type from the procy.GetAllDDCs method and see what it is returning.
The error message you are getting shows that the DataList1 control cannot find a way to enumerate the items for binding.