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.
Related
I'm writing a console app to retrieve JSON data from a 3rd party API. I have no control over the API data structures or functionality.
Several of the calls I make will return multiple 'pages' of data. The data is a collection of objects of a certain type e.g. User.
I have created classes in my app to match the various data types from the API.
public class User
{
[JsonProperty("id")]
public int ID { get; set; }
[JsonProperty("first_name")]
public string FirstName { get; set; }
[JsonProperty("last_name")]
public string LastName { get; set; }
}
public class FooBar
{
[JsonProperty("foo")]
public string Foo { get; set; }
[JsonProperty("bar")]
public string Bar { get; set; }
}
The API response is always in the same format for these calls. While the actual object types in the "data" array will differ depending on what call has been made.
{
"paging":{"page":1},
"data":[{<object>}, {<object>}, {<object>},...]
}
I have created a class to try to deserialize these. The dynamic[] type for the Data property is for illustrative purposes and I am happy to change it if there is a better approach.
public class ApiResponseObject
{
[JsonProperty("paging")]
public Paging PagingInfo { get; set; }
[JsonProperty("data")]
public dynamic[] Data { get; set; }
}
And I would like to have the Data collection resolve to the appropriate type for the objects it contains. e.g.
string userJson = "{\"paging\":{\"page\":1},\"data\":[{\"id\":1,\"first_name\":\"Joe\",\"last_name\":\"Bloggs\"},{\"id\":2,\"first_name\":\"Jane\",\"last_name\":\"Doe\"}]}"; // json string would come from API
string foobarJson = "{\"paging\":{\"page\":1},\"data\":[{\"foo\":\"Lorem\",\"bar\":\"Ipsum\"},{\"foo\":\"Dolor\",\"bar\":\"Amet\"}]}";
var userResponse = JsonConvert.DeserializeObject<ApiResponseObject>(userJson);
var foobarResponse = JsonConvert.DeserializeObject<ApiResponseObject>(foobarJson);
The deserialization succeeds but the Data collection is of type JObject and cannot be cast into the correct type (User, FooBar).
I am trying to avoid having to write specific response object classes for each request if possible.
I will know what type of object I am expecting in the collection when I am requesting it so I could pass that type to the deserializer but I'm not clear on how to achieve that in this particular scenario.
Something like the below psuedo code would be ideal.
var userResponse = JsonConvert.DeserializeObject<ApiResponseObject<User>>(userJson);
Thanks for your help!
You can use the generic type T, like this :
public class ApiResponseObject<T>
{
[JsonProperty("paging")]
public Paging PagingInfo { get; set; }
[JsonProperty("data")]
public T[] Data { get; set; }
}
I've got an ASP.NET Web API and I'm using the ASP.NET Web API Help Page to automatically generate documentation for my API. Everything works well except for one property on my model that is read only. My model looks like this:
[DataContract]
public class EventViewModel
{
[DataMember]
public int ProjectId { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string ProjectUrl
{
get
{
return MvcUrlHelper.BuildUrl(MvcUrlType.Project, new MvcUrlContent()
{
ProjectSlug = ProjectSlug,
OrganizationDomain = OrganizationDomain,
OrganizationSlug = OrganizationSlug
});
}
}
public string OrganizationSlug { get; set; }
public string OrganizationDomain { get; set; }
public string ProjectSlug { get; set; }
}
I get the following error when it tries to generate the sample response for an action returning this model:
An exception has occurred while using the formatter
'JsonMediaTypeFormatter' to generate sample for media type
'application/json'. Exception message: Error getting value from
'ProjectUrl' on 'WebApi.Models.EventViewModel'.
If I comment out the ProjectUrl property then the sample response generates fine. Any idea how to tell it to treat that property as a normal string, or better yet provide what the sample value should be for that property?
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 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.
I am creating a Web Service using ASP.NET C#. I am sending various data types from the webservice so I use the following structure.
public enum WS_ServiceResponseResult
{
Success,
Failure,
}
public class WS_ServiceResponse
{
public WS_ServiceResponseResult result { get; set; }
public object data { get; set; }
}
public class WS_User
{
public long id{ get; set; }
public string name{ get; set; }
}
Webservice Sample Method
[WebMethod(EnableSession = true)]
public WS_ServiceResponse LogIn(string username, string pasword)
{
WS_ServiceResponse osr = new WS_ServiceResponse();
long userID = UserController.checkLogin(username, pasword);
if (userID != 0)
{
osr.result = WS_ServiceResponseResult.Success;
osr.data = new WS_User() { id = userID, name = username };
}
else
{
osr.result = WS_ServiceResponseResult.Failure;
osr.data = "Invalid username/password!";
}
return osr;
}
I am using two client types, javascript and C#.NET Windows Form. When I call from javascript I get no problem and the osr.data is filled with WS_User. So i can use osr.data.id easily. But when I use from C#.NET (proxy is generated using "Add Web Reference") I can successfully call but when the result arrives I get a Soap Exception
{System.Web.Services.Protocols.SoapException:
System.Web.Services.Protocols.SoapException:
Server was unable to process request.
---> System.InvalidOperationException: There was an error generating the XML
document. ... ...
What am I missing? I Guess object is not well defined and causing the problems. What are the workarounds?
Thanks
Maksud
Addition:
If add the following dummy method, then it works nicely. Hope it helps, to get the solution.
[WebMethod]
public WS_User Dummy()
{
return new WS_User();
}
I had a similar Problem returning an "object" (multiple classes possible)
Here is a sample code:
[Serializable()]
[XmlRoot(ElementName="Object")]
public sealed class XMLObject
{
private Object _Object;
[XmlElement(Type=typeof(App.Projekte.Projekt), ElementName="Projekt")]
[XmlElement(Type=typeof(App.Projekte.Task), ElementName="Task")]
[XmlElement(Type=typeof(App.Projekte.Mitarbeiter), ElementName="Mitarbeiter")]
public Object Object
{
get
{
return _Object;
}
set
{
_Object = value;
}
}
}
I think you should change your code this way:
[XmlRoot(ElementName="ServiceResponse")]
public class WS_ServiceResponse
{
public WS_ServiceResponseResult result { get; set; }
[XmlElement(Type=typeof(WS_User), ElementName="WS_User")]
[XmlElement(Type=typeof(string), ElementName="Text")]
public object data { get; set; }
}