Chatbot Language Translation: Saving the Detected Language for Response Translation - c#

I have a chatbot that is implementing translation middleware. The middleware detects the incoming language and translates the query into English. I have been working to save the detected language as a variable to pass for translating the response into the user's language, but have hit a roadblock.
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
var body = new object[] { new { Text = turnContext.Activity.Text } };
var requestBody = JsonConvert.SerializeObject(body);
//Console.WriteLine("------------------------------------------------------------------------");
//Console.WriteLine(requestBody);
//Console.WriteLine("------------------------------------------------------------------------");
//var languageChoice = "de";
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
//var uri = "https://api.cognitive.microsofttranslator.com" + "/translate?api-version=3.0" + "&from=" + languageChoice + "&to=" + "en";
var uri = "https://api.cognitive.microsofttranslator.com" + "/translate?api-version=3.0" + "&to=" + "en";
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(uri);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", _configuration["TranslatorKey"]);
request.Headers.Add("Ocp-Apim-Subscription-Region", "westus2");
var translatedResponse = await client.SendAsync(request);
var responseBody = await translatedResponse.Content.ReadAsStringAsync();
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine(responseBody);
Console.WriteLine("------------------------------------------------------------------------");
var translation = JsonConvert.DeserializeObject<TranslatorResponse[]>(responseBody);
var detectedLanguage = JsonConvert.DeserializeObject<DetectLanguage[]>(responseBody);
var ourResponse = detectedLanguage?.FirstOrDefault()?.DetectedLanguage?.FirstOrDefault()?.Language.ToString();
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine(ourResponse);
Console.WriteLine("------------------------------------------------------------------------");
//Console.WriteLine("------------------------------------------------------------------------");
//Console.WriteLine(turnContext.Activity.Text);
//Console.WriteLine(translation?.FirstOrDefault()?.Translations?.FirstOrDefault()?.Text.ToString());
//Console.WriteLine("------------------------------------------------------------------------");
// Update the translation field
turnContext.Activity.Text = translation?.FirstOrDefault()?.Translations?.FirstOrDefault()?.Text.ToString();
}
// First, we use the dispatch model to determine which cognitive service (LUIS or QnA) to use.
var recognizerResult = await _botServices.Dispatch.RecognizeAsync(turnContext, cancellationToken);
// Top intent tell us which cognitive service to use.
var topIntent = recognizerResult.GetTopScoringIntent();
// Next, we call the dispatcher with the top intent.
// ***** ERROR *****
await DispatchToTopIntentAsync(turnContext, topIntent.intent, recognizerResult, cancellationToken);
}
Using the console log from responseBody:
[{"detectedLanguage":{"language":"es","score":1.0},"translations":[{"text":"Hello","to":"en"}]}]
We have determined that responseBody is an Object array that contains an attribute “detectedLanguage”, an object, with the attributes “language” and “score”.
To retrieve the variable “language” from the object “detectedLanguage” we have made the following attempt, using “turnContext.Activity.Text” which is returned as the translated text as an example to follow.
We also added two internal classes that mimic the implementation of “turnContext.Activity.Text”:
1)
namespace Microsoft.BotBuilderSamples.Translation.Model
{
/// <summary>
/// Array of translated results from Translator API v3.
/// </summary>
internal class TranslatorResponse
{
[JsonProperty("translations")]
public IEnumerable<TranslatorResult> Translations { get; set; }
}
internal class DetectLanguage
{
[JsonProperty("detectedLanguage")]
public IEnumerable<LanguageResult> DetectedLanguage { get; set; }
}
}
using Newtonsoft.Json;
namespace Microsoft.BotBuilderSamples.Translation.Model
{
/// <summary>
/// Translation result from Translator API v3.
/// </summary>
internal class TranslatorResult
{
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("to")]
public string To { get; set; }
}
internal class LanguageResult
{
[JsonProperty("language")]
public string Language { get; set; }
}
}
However, when we try to test and display “ourResponse” in the console we are met with the following error message:
fail: Microsoft.Bot.Builder.Integration.AspNet.Core.BotFrameworkHttpAdapter[0]
[OnTurnError] unhandled error : Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable`1[Microsoft.BotBuilderSamples.Translation.Model.LanguageResult]' 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 '[0].detectedLanguage.language', line 1, position 33.
We have determined that we are hitting this error because “detectedLanguage” is not an array like “translations” is. (Shown in console output below):
[{"detectedLanguage":{"language":"es","score":1.0},"translations":[{"text":"Hello","to":"en"}]}]
My question is how do we adjust this implementation to work with the object detectedLanguage outside of an array, or how do we adjust detectedLanguage to be contained within a string to work with the implementation?

Your class structure doesn't match your json. What you want is the following:
internal class DetectedLanguage
{
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("score")]
public double Score { get; set; }
}
internal class TranslatorResult
{
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("to")]
public string To { get; set; }
}
internal class TranslatorResponse
{
[JsonProperty("detectedLanguage")]
public DetectedLanguage DetectedLanguage { get; set; }
[JsonProperty("translations")]
public IEnumerable<TranslatorResult> Translations { get; set; }
}
Note how DetectedLanguage should be represented as a single object ON the TranslatorResponse object, which you are not doing currently. In addition, the Language property of DetectedLanguage is also a single property, not a collection.

Related

How can I return XML from BeforeSendRequest and AfterReceiveReply to the calling method in a thread-safe way?

We have a console application using the Azure WebJob SDK. The WebJob relies on a WCF service using SOAP, which it accesses through a DLL we wrote that wraps the auto-generated WCF types in something a bit more friendly.
For logging purposes, we want to save the request and response XML bodies for requests that we make. These XML bodies would be saved in our database. But, because the WCF code lives in a low-level DLL, it has no concept of our database and can't save to it.
The DLL uses Microsoft's DI extensions to register types, and the WebJob calls into it like this:
class WebJobClass
{
IWCFWrapperClient _wcfWrapperClient;
public WebJobClass(IWCFWrapperClient wcfWrapperClient)
{
_wcfWrapperClient = wcfWrapperClient;
}
public async Task DoThing()
{
var callResult = await _wcfWrapperClient.CallWCFService();
}
}
IWCFWrapperClient looks like this:
class WCFWrapperClient : IWCFWrapperClient
{
IWCF _wcf; // auto-generated by VS, stored in Reference.cs
public async Task<object> CallWCFService()
{
return await _wcf.Call(); // another auto-generated method
}
}
I've implemented an IClientMessageInspector, and it works fine to get me the XML request/response, but I don't have a way to pass it back up to WCFWrapperClient.CallWCFService so that it can be returned to WebJobClass.DoThing(), who could then save it to the database.
The problem is multithreading. WebJobs, IIRC, will run multiple requests in parallel, calling into the DLL from multiple threads. This means we can't, say, share a static property LastRequestXmlBody since multiple threads could overwrite it. We also can't, say, give each call a Guid or something since there's no way to pass anything from IWCFWrapperClient.CallWCFService into the auto-generated IWCF.Call except what was auto-generated.
So, how can I return XML to WebJobClass.DoThing in a thread-safe way?
I was able to find a solution that uses ConcurrentDictionary<TKey, TValue>, but it's a bit ugly.
First, I amended the auto-generated classes in Reference.cs with a new property Guid InternalCorrelationId. Since the auto-generated classes are partial, this can be done in separate files that aren't changed when the client is regenerated.
public partial class AutoGeneratedWCFType
{
private Guid InternalCorrelationIdField;
[System.Runtime.Serialization.DataMember()]
public Guid InternalCorrelationId
{
get { return InternalCorrelationIdField; }
set { InternalCorrelationIdField = value; }
}
}
Next, I made all my request DTO types derive from a type named RequestBase, and all my response DTO types derive from a typed named ResponseBase, so I could handle them generically:
public abstract class RequestBase
{
public Guid InternalCorrelationId { get; set; }
}
public abstract class ResponseBase
{
public string RequestXml { get; set; }
public string ResponseXml { get; set; }
}
I then added a type RequestCorrelator that simply holds on to a ConcurrentDictionary<Guid, XmlRequestResponse>:
public sealed class RequestCorrelator : IRequestCorrelator
{
public ConcurrentDictionary<Guid, XmlRequestResponse> PendingCalls { get; }
public RequestCorrelator() => PendingCalls = new ConcurrentDictionary<Guid, XmlRequestResponse>();
}
public sealed class XmlRequestResponse
{
public string RequestXml { get; set; }
public string ResponseXml { get; set; }
}
RequestCorrelator is its own type for DI purposes - you may just be able to use a ConcurrentDictionary<TKey, TValue> directly.
Finally, we have the code that actually grabs the XML, a type implementing IClientMessageInspector:
public sealed class ClientMessageProvider : IClientMessageInspector
{
private readonly IRequestCorrelator _requestCorrelator;
public ClientMessageProvider(IRequestCorrelator requestCorrelator) =>
_requestCorrelator = requestCorrelator;
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
var requestXml = request.ToString();
var internalCorrelationId = GetInternalCorrelationId(requestXml);
if (internalCorrelationId != null)
{
if (_requestCorrelator.PendingCalls.TryGetValue(internalCorrelationId.Value,
out var requestResponse))
{
requestResponse.RequestXml = requestXml;
}
request = RemoveInternalCorrelationId(request);
}
return internalCorrelationId;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
// WCF can internally correlate a request between BeforeSendRequest and
// AfterReceiveReply. We reuse the same correlation ID we added to the
// XML as our correlation state.
var responseXml = reply.ToString();
var internalCorrelationId = (correlationState is Guid guid)
? guid
: default;
if (_requestCorrelator.PendingCalls.TryGetValue(internalCorrelationId,
out var requestResponse))
{
requestResponse.ResponseXml = responseXml;
}
}
private static Guid? GetInternalCorrelationId(string requestXml)
{
var document = XDocument.Parse(requestXml);
var internalCorrelationIdElement = /* You'll have to write this yourself;
every WCF XML request is different. */
return internalCorrelationIdElement != null
? Guid.Parse(internalCorrelationIdElement.Value)
: null;
}
private static Message RemoveInternalCorrelationId(Message oldMessage)
{
// https://stackoverflow.com/a/35639900/2709212
var buffer = oldMessage.CreateBufferedCopy(2 * 1024 * 1024);
var tempMessage = buffer.CreateMessage();
var dictionaryReader = tempMessage.GetReaderAtBodyContents();
var document = new XmlDocument();
document.Load(dictionaryReader);
dictionaryReader.Close();
var internalCorrelationIdNode = /* You'll also have to write this yourself. */
var parent = internalCorrelationIdNode.ParentNode;
parent.RemoveChild(internalCorrelationIdNode);
var memoryStream = new MemoryStream();
var xmlWriter = XmlWriter.Create(memoryStream);
document.Save(xmlWriter);
xmlWriter.Flush();
xmlWriter.Close();
memoryStream.Position = 0;
var xmlReader = XmlReader.Create(memoryStream);
var newMessage = Message.CreateMessage(oldMessage.Version, null, xmlReader);
newMessage.Headers.CopyHeadersFrom(oldMessage);
newMessage.Properties.CopyProperties(oldMessage.Properties);
return newMessage;
}
}
In short, this type:
Finds the correlation ID in the XML request.
Finds the XmlRequestResponse with the same correlation ID and adds the request to it.
Removes the correlation ID element so that the service doesn't get elements they didn't expect.
After receiving a reply, uses correlationState to find the XmlRequestResponse and write the response XML to it.
Now all we have to do is change IWCFWrapperClient:
private async Task<TDtoResult> ExecuteCallWithLogging<TDtoRequest,
TWcfRequest,
TWcfResponse,
TDtoResult>(TDtoRequest request,
Func<TDtoRequest, TWcfRequest> dtoToWcfConverter,
Func<TWcfRequest, Task<TWcfResponse>> wcfCall,
Func<TWcfResponse, TDtoResult> wcfToDtoConverter)
where TDtoRequest : CorrelationBase
where TDtoResult : WcfBase
{
request.InternalCorrelationId = Guid.NewGuid();
var xmlRequestResponse = new XmlRequestResponse();
_requestCorrelator.PendingCalls.GetOrAdd(request.InternalCorrelationId,
xmlRequestResponse);
var response = await contractingCall(dtoToWcfConverter(request));
_requestCorrelator.PendingCalls.TryRemove(request.InternalCorrelationId, out _);
return wcfToDtoConverter(response).WithRequestResponse(xmlRequestResponse);
}
public async Task<DoThingResponseDto> DoThing(DoThingRequestDto request) =>
await ExecuteCallWithLogging(request,
r => r.ToWcfModel(),
async d => await _wcf.Call(d),
d => d.ToDtoModel());
WithRequestResponse is implemented as follows:
public static T WithRequestResponse<T>(this T item, XmlRequestResponse requestResponse)
where T : ResponseBase
{
item.RequestXml = requestResponse?.RequestXml;
item.ResponseXml = requestResponse?.ResponseXml;
return item;
}
And there we go. WCF calls that return their XML in the response object rather than just something you can print to console or log to a file.

Properly deserialize object with RootObject [duplicate]

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
}

Unable to Serialize/Deserialize List<> object into JSON

I am working on 2 web applications; A & B. now i have a shared class named CRUDOutput as follow on both web applications:-
public class CRUDOutput
{
public Operation4 operation { get; set; }
}
public class Operation4
{
public Result result { get; set; }
public string name { get; set; }
}
public class Result
{
public string status { get; set; }
public string message { get; set; }
}
now inside web application A i am returning the following:-
[HttpPost]
public ActionResult CreateResource(CreateResource cr)
{
List<CRUDOutput> co = new List<CRUDOutput>();
co.Add(JsonConvert.DeserializeObject<CRUDOutput>(crudoutput));
co.Add(JsonConvert.DeserializeObject<CRUDOutput>(crudoutput2));
return Json(JsonConvert.SerializeObject(co));
}
now from web application B, i am calling the action method as follow:-
try
{
using (WebClient wc = new WebClient())
{
string url = "https://localhost:44302/" + "Home/CreateResource";
Uri uri = new Uri(url);
wc.Headers.Add(HttpRequestHeader.ContentType, "application/json");
output = wc.UploadString(uri, data);
}
}
catch (WebException e)
{
}
List<CRUDOutput> result = JsonConvert.DeserializeObject<List< CRUDOutput>>(output);
but i will get the following exception when i tried to deserialize the output:-
Error converting value
"[{"operation":{"result":{"status":"Success","message":"Resource has
been added successfully to ......"},"name":"CREATE
RESOURCE"}},{"operation":{"result":{"status":"Failed","message":"Account
addition "},"name":"ADD ACCOUNTS"}}]" to type
'System.Collections.Generic.List`1[S.ViewModels.CRUDOutput]'. Path '',
line 1, position 464.
now the JSON return from web application A will be as follow:-
"\"[{\\\"operation\\\":{\\\"result\\\":{\\\"status\\\":\\\"Success\\\",\\\"message\\\":\\\"Resource 123 rfrf has been added successfully \\\"},\\\"name\\\":\\\"CREATE RESOURCE\\\"}},{\\\"operation\\\":{\\\"result\\\":{\\\"status\\\":\\\"Failed\\\",\\\"message\\\":\\\"Account addition \\\"},\\\"name\\\":\\\"ADD ACCOUNTS\\\"}}]\""
so can anyone advice why i am unable to deserialize to a list of objects?
The output as you've pasted is encoded as JSON twice. Compare the difference between:
"\"[{\\\"operation\\\":{\\\"result\\\":{\\\"status\\\":\\\"Success\\\",\\\"message\\\":\\\"Resource 123 rfrf has been added successfully \\\"},\\\"name\\\":\\\"CREATE RESOURCE\\\"}},{\\\"operation\\\":{\\\"result\\\":{\\\"status\\\":\\\"Failed\\\",\\\"message\\\":\\\"Account addition \\\"},\\\"name\\\":\\\"ADD ACCOUNTS\\\"}}]\""
and
"[{\"operation\":{\"result\":{\"status\":\"Success\",\"message\":\"Resource 123 rfrf has been added successfully \"},\"name\":\"CREATE RESOURCE\"}},{\"operation\":{\"result\":{\"status\":\"Failed\",\"message\":\"Account addition \"},\"name\":\"ADD ACCOUNTS\"}}]"
This happens because you're encoding the result as Json twice. Replace:
return Json(JsonConvert.SerializeObject(result));
with
return Json(result); // This encodes as JSON automatically

Convert Json Singleton into List Phone 81 UAP

I am using http client to return a json response from a webservice. The example I am following here is from code project tutorial. However its example only returns into a var, it was created for the method to be called on screen I am changing it to be called from within a class. I have removed the webservice for security.
My Main question is how would I change this function to return a List of cinemas instead of the var variable I have a class created as such. I tried changing var into List but i noticed json.net handles this list so I need return the var as a known object instead I think?.
public class City
{
public string id { get; set; }
public string timing_title { get; set; }
}
public class Citys
{
public List<City> city { get; set; }
}
I just don't know what to do to convert this so it returns a list of citys for me to use in function.
This is a list of example json data returned.
{"city":[{"id":"5521","timing_title":"Lahore"},{"id":"5517","timing_title":"Karachi"},{"id":"5538","timing_title":"Islamabad"},{"id":"5535","timing_title":"Rawalpindi"},{"id":"5518","timing_title":"Hyderabad"},{"id":"5512","timing_title":"Faisalabad"},{"id":"8028","timing_title":"Gujranwala"},{"id":"8027","timing_title":"Gujrat"}]}
public async void GetCinemasList()
{
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("webserviceurl");
var url = "index.php/webservice/upcoming_movie";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsStringAsync();
var cityData = JsonConvert.DeserializeObject<City>(data.Result.ToString());
}
}
}
catch (Exception ex)
{
// MessageBox.Show("Some Error Occured");
}
}
You have a string holding a JSON value.
You can parse and iterate through JSON values like this:
var data = "{\"city\":[{\"id\":\"5521\",\"timing_title\":\"Lahore\"},{\"id\":\"5517\",\"timing_title\":\"Karachi\"},{\"id\":\"5538\",\"timing_title\":\"Islamabad\"},{\"id\":\"5535\",\"timing_title\":\"Rawalpindi\"},{\"id\":\"5518\",\"timing_title\":\"Hyderabad\"},{\"id\":\"5512\",\"timing_title\":\"Faisalabad\"},{\"id\":\"8028\",\"timing_title\":\"Gujranwala\"},{\"id\":\"8027\",\"timing_title\":\"Gujrat\"}]}";
JsonObject rootObject;
if (JsonObject.TryParse(data, out rootObject))
{
JsonArray cityArray = rootObject.GetNamedArray("city");
foreach (var jsonValue in cityArray)
{
JsonObject cityObject = jsonValue.GetObject();
Debug.WriteLine(cityObject.GetNamedString("timing_title"));
}
}
else
{
// Invalid JSON data.
}
Output:
Lahore
Karachi
Islamabad
Rawalpindi
Hyderabad
Faisalabad
Gujranwala
Gujrat

Deserialize list of JSON objects

I got a Windows Phone 8.1 app.
I am trying to parse a list of objects returned by my Web API call.
On my server I have this code:
Default.aspx:
[WebMethod]
public static List<Shared.PremisesResponse> GetPremises(string emailaddress)
{
Premises premises = new Premises();
return premises.GetPremises(emailaddress);
}
In that premise object class
public List<Shared.PremisesResponse> GetPremises(string emailAlias)
{
DAL dal = new DAL();
List<Shared.PremisesResponse> premises = new List<Shared.PremisesResponse>();
try
{
DataSet dtMacs = dal.GetMacs(emailAlias);
for (int index = 0; index < dtMacs.Tables[0].Rows.Count; index++)
{
Shared.PremisesResponse itemMAC1 = new Shared.PremisesResponse();
itemMAC1.PremiseName = dtMacs.Tables[0].Rows[index]["PremiseName"].ToString().Trim();
itemMAC1.Alias = dtMacs.Tables[0].Rows[index]["Alias"].ToString().Trim();
premises.Add(itemMAC1);
}
}
catch (Exception ex)
{
Email2.SendError("Premises.GetPremises:" + ex.ToString(), emailAlias);
Shared.PremisesResponse itemMAC1 = new Shared.PremisesResponse();
itemMAC1.PremiseName = "ERROR";
itemMAC1.Alias = ex.ToString();
premises.Add(itemMAC1);
}
return premises;
}
The class Shared.Premise:
public class PremisesResponse
{
public string PremiseName;
public string Alias;
}
In my WP8.1 client app:
public async static Task<List<D2>> GetPremises( string emailaddress)
{
List<D2> premises = new List<D2>();
try
{
using (var client = new HttpClient())
{
var resp = await client.PostAsJsonAsync("http://my url/NativeApp/Default.aspx/GetPremises",
new { emailaddress = emailaddress });
var str = await resp.Content.ReadAsStringAsync();
var premisesResponse = JsonConvert.DeserializeObject<List<D2>>(str);
foreach (var pr in premisesResponse)
{
D2 d2 = new D2();
d2.Alias = pr.Alias;
d2.PremiseName = pr.PremiseName;
premises.Add(d2);
}
}
}
catch (Exception ex)
{
//evMessage(Enums.MessageType.Error, serverRegister);
}
return premises;
}
And the objects I am using in my client:
public class D2
{
public string __type { get; set; }
public string PremiseName;
public string Alias;
}
public class PremisesResponse
{
public D2 d { get; set; }
}
'var str' returns this value:
{"d":[{"__type":"InformedMotionBiz.Shared+PremisesResponse","PremiseName":"Informatica 2000","Alias":"9A5C3-E1945-3D315-BB43C"},{"__type":"InformedMotionBiz.Shared+PremisesResponse","PremiseName":"My Office","Alias":"40387-69918-FC22F-C444B"}]}
The error occurs on this line:
var premisesResponse = JsonConvert.DeserializeObject<List<PremisesResponse>>(str);
The error message is:
[Informed.D2]' 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 'd', line 1, position 5.
I have no problems returning a single value, just with returning a list of this object.
Any pointers would be helpful.
Thanks
You're trying to deserialize a List<D2> rather than a single D2 object:
public class PremisesResponse
{
public D2[] d { get; set; }
}
And then simply:
PremisesResponse response = JsonConvert.DeserializeObject<PremisesResponse>(str);

Categories