Unable to Serialize/Deserialize List<> object into JSON - c#

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

Related

C# Having Trouble Asynchronously Downloading Multiple Files in Parallel on Console Application [duplicate]

This question already has answers here:
My console app shutdown prematurely when using async / await?
(4 answers)
Program exits upon calling await
(3 answers)
Closed 2 years ago.
Before you all go on a rampage about how this is a duplicate question, I have spent two days working on this issue, watching youtube tutorials on asynchronous programming, surfing similar stackoverflow posts etc, and I cannot for the life of me figure out how to apply Asynchronous Parallel Downloading of files into my project.
First things first, some background:
I am creating a program that, when given a query input via the user, will make a call to the twitch API and download clips.
My program is two parts
1- A web scraper that generates a .json file with all details needed to download files and
2 - A downloader.
Part 1 works perfectly fine and generates the .json files no trouble.
My Downloader contains reference to a Data class that is a handler for common properties and methods like my ClientID, Authentication, OutputPath, JsonFile, QueryURL. It also contains methods to give values to these properties.
Here are the two methods of my FileDownloader.cs that are the problem:
public async static void DownloadAllFiles(Data clientData)
{
data = clientData;
data.OutputFolderExists();
// Deserialize .json file and get ClipInfo list
List<ClipInfo> clips = JsonConvert.DeserializeObject<List<ClipInfo>>(File.ReadAllText(data.JsonFile));
tasks = new List<Task>();
foreach(ClipInfo clip in clips)
{
tasks.Add(DownloadFilesAsync(clip));
}
await Task.WhenAll(tasks);
}
private async static Task DownloadFilesAsync(ClipInfo clip)
{
WebClient client = new WebClient();
string url = GetClipURL(clip);
string filepath = data.OutputPath + clip.id + ".mp4";
await client.DownloadFileTaskAsync(new Uri(url), filepath);
}
This is only one of my many attempts of downloading files, one which I got the idea from this post:
stackoverflow_link
I have also tried methods like the following from a YouTube video by IAmTimCorey:
video_link
I have spent many an hour tackling this problem, and I honestly can't figure out why it won't work with any of my attempts. I would vastly appreciate your help.
Thanks,
Ben
Below is the entirety of my code, should anyone need it for any reason.
Code Structure:
The only external libraries I have downloaded is Newtonsoft.Json
ClipInfo.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Downloader
{
public class ClipInfo
{
public string id { get; set; }
public string url { get; set; }
public string embed_url { get; set; }
public string broadcaster_id { get; set; }
public string broadcaster_name { get; set; }
public string creator_id { get; set; }
public string creator_name { get; set; }
public string video_id { get; set; }
public string game_id { get; set; }
public string language { get; set; }
public string title { get; set; }
public int view_count { get; set; }
public DateTime created_at { get; set; }
public string thumbnail_url { get; set; }
}
}
Pagination.cs
namespace Downloader
{
public class Pagination
{
public string cursor { get; set; }
}
}
Root.cs
using System.Collections.Generic;
namespace Downloader
{
public class Root
{
public List<ClipInfo> data { get; set; }
public Pagination pagination { get; set; }
}
}
Data.cs
using System;
using System.IO;
namespace Downloader
{
public class Data
{
private static string directory = Directory.GetCurrentDirectory();
private readonly static string defaultJsonFile = directory + #"\clips.json";
private readonly static string defaultOutputPath = directory + #"\Clips\";
private readonly static string clipsLink = "https://api.twitch.tv/helix/clips?";
public string OutputPath { get; set; }
public string JsonFile { get; set; }
public string ClientID { get; private set; }
public string Authentication { get; private set; }
public string QueryURL { get; private set; }
public Data()
{
OutputPath = defaultOutputPath;
JsonFile = defaultJsonFile;
}
public Data(string clientID, string authentication)
{
ClientID = clientID;
Authentication = authentication;
OutputPath = defaultOutputPath;
JsonFile = defaultJsonFile;
}
public Data(string clientID, string authentication, string outputPath)
{
ClientID = clientID;
Authentication = authentication;
OutputPath = directory + #"\" + outputPath + #"\";
JsonFile = OutputPath + outputPath + ".json";
}
public void GetQuery()
{
Console.Write("Please enter your query: ");
QueryURL = clipsLink + Console.ReadLine();
}
public void GetClientID()
{
Console.WriteLine("Enter your client ID");
ClientID = Console.ReadLine();
}
public void GetAuthentication()
{
Console.WriteLine("Enter your Authentication");
Authentication = Console.ReadLine();
}
public void OutputFolderExists()
{
if (!Directory.Exists(OutputPath))
{
Directory.CreateDirectory(OutputPath);
}
}
}
}
JsonGenerator.cs
using System;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Linq;
namespace Downloader
{
public static class JsonGenerator
{
// This class has no constructor.
// You call the Generate methods, passing in all required data.
// The file will then be generated.
private static Data data;
public static async Task Generate(Data clientData)
{
data = clientData;
string responseContent = null;
// Loop that runs until the api request goes through
bool authError = true;
while (authError)
{
authError = false;
try
{
responseContent = await GetHttpResponse();
}
catch (HttpRequestException)
{
Console.WriteLine("Invalid authentication, please enter client-ID and authentication again!");
data.GetClientID();
data.GetAuthentication();
authError = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
authError = true;
}
}
data.OutputFolderExists();
GenerateJson(responseContent);
}
// Returns the contents of the resopnse to the api call as a string
private static async Task<string> GetHttpResponse()
{
// Creating client
HttpClient client = new HttpClient();
if (data.QueryURL == null)
{
data.GetQuery();
}
// Setting up request
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, data.QueryURL);
// Adding Headers to request
requestMessage.Headers.Add("client-id", data.ClientID);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", data.Authentication);
// Receiving response to the request
HttpResponseMessage responseMessage = await client.SendAsync(requestMessage);
// Gets the content of the response as a string
string responseContent = await responseMessage.Content.ReadAsStringAsync();
return responseContent;
}
// Generates or adds to the .json file that contains data on each clip
private static void GenerateJson(string responseContent)
{
// Parses the data from the response to the api request
Root responseResult = JsonConvert.DeserializeObject<Root>(responseContent);
// If the file doesn't exist, we need to create it and add a '[' at the start
if (!File.Exists(data.JsonFile))
{
FileStream file = File.Create(data.JsonFile);
file.Close();
// The array of json objects needs to be wrapped inside []
File.AppendAllText(data.JsonFile, "[\n");
}
else
{
// For a pre-existing .json file, The last object won't have a comma at the
// end of it so we need to add it now, before we add more objects
string[] jsonLines = File.ReadAllLines(data.JsonFile);
File.WriteAllLines(data.JsonFile, jsonLines.Take(jsonLines.Length - 1).ToArray());
File.AppendAllText(data.JsonFile, ",");
}
// If the file already exists, but there was no [ at the start for whatever reason,
// we need to add it
if (File.ReadAllText(data.JsonFile).Length == 0 || File.ReadAllText(data.JsonFile)[0] != '[')
{
File.WriteAllText(data.JsonFile, "[\n" + File.ReadAllText(data.JsonFile));
}
string json;
// Loops through each ClipInfo object that the api returned
for (int i = 0; i < responseResult.data.Count; i++)
{
// Serializes the ClipInfo object into a json style string
json = JsonConvert.SerializeObject(responseResult.data[i]);
// Adds the serialized contents of ClipInfo to the .json file
File.AppendAllText(data.JsonFile, json);
if (i != responseResult.data.Count - 1)
{
// All objects except the last require a comma at the end of the
// object in order to correctly format the array of json objects
File.AppendAllText(data.JsonFile, ",");
}
// Adds new line after object entry
File.AppendAllText(data.JsonFile, "\n");
}
// Adds the ] at the end of the file to close off the json objects array
File.AppendAllText(data.JsonFile, "]");
}
}
}
FileDownloader.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
namespace Downloader
{
public class FileDownloader
{
private static Data data;
private static List<Task> tasks;
public async static void DownloadAllFiles(Data clientData)
{
data = clientData;
data.OutputFolderExists();
// Deserialize .json file and get ClipInfo list
List<ClipInfo> clips = JsonConvert.DeserializeObject<List<ClipInfo>>(File.ReadAllText(data.JsonFile));
tasks = new List<Task>();
foreach (ClipInfo clip in clips)
{
tasks.Add(DownloadFilesAsync(clip));
}
await Task.WhenAll(tasks);
}
private static void GetData()
{
if (data.ClientID == null)
{
data.GetClientID();
}
if (data.Authentication == null)
{
data.GetAuthentication();
}
if (data.QueryURL == null)
{
data.GetQuery();
}
}
private static string GetClipURL(ClipInfo clip)
{
// Example thumbnail URL:
// https://clips-media-assets2.twitch.tv/AT-cm%7C902106752-preview-480x272.jpg
// You can get the URL of the location of clip.mp4
// by removing the -preview.... from the thumbnail url */
string url = clip.thumbnail_url;
url = url.Substring(0, url.IndexOf("-preview")) + ".mp4";
return url;
}
private async static Task DownloadFilesAsync(ClipInfo clip)
{
WebClient client = new WebClient();
string url = GetClipURL(clip);
string filepath = data.OutputPath + clip.id + ".mp4";
await client.DownloadFileTaskAsync(new Uri(url), filepath);
}
private static void FileDownloadComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
tasks.Remove((Task)sender);
}
}
}
Program.cs
using System;
using System.Threading.Tasks;
using Downloader;
namespace ClipDownloader
{
class Program
{
private static string clientID = "{your_client_id}";
private static string authentication = "{your_authentication}";
async static Task Main(string[] args)
{
Console.WriteLine("Enter your output path");
string outputPath = Console.ReadLine();
Data data = new Data(clientID, authentication, outputPath);
Console.WriteLine(data.OutputPath);
//await JsonGenerator.Generate(data);
FileDownloader.DownloadAllFiles(data);
}
}
}
The example query I usually type in is "game_id=510218"
async void is your problem
Change
public static async void DownloadAllFiles(Data clientData)
To
public static async Task DownloadAllFiles(Data clientData)
Then you can await it
await FileDownloader.DownloadAllFiles(data);
The longer story:
async void runs unobserved (fire and forget). You can't wait for them to finish. In essence as soon as your program starts the task, it finishes, and tears down the App Domain and all your sub tasks, leading you to believe nothing is working.
I'm trying to stay on topic here as best as I can, but when using JsonConvert.DeserializeObject{T}, isn't T suppose to be an encapsulating root object type? I have never used it the way you're using it, so I'm just curious if that might be your bug. I could be completely wrong, and spare me if i am, but JSON is key:value based. Deserializing directly to a List doesn't really make sense. Unless there is a special case in the deserializer? List would be a file that's purely an array of ClipInfo values being deserialized into the members of List{T}(private T[] _items, private int _size, etc.) It needs a parent root object.
// current JSON file format implication(which i dont think is valid JSON?(correct me please)
clips:
[
// clip 1
{ "id": "", "url": "" },
// clip N
{ "id": "", "url": "" },
]
// correct(?) JSON file format
{ // { } is the outer encasing object
clips:
[
// clip 1
{ "id": "", "url": "" },
// clip N
{ "id": "", "url": "" },
]
}
class ClipInfoJSONFile
{
public List<ClipInfo> Info { get; set; }
}
var clipInfoList = JsonConverter.DeserializeObject<ClipInfoJSONFile>(...);

Chatbot Language Translation: Saving the Detected Language for Response Translation

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.

Converting JSON to C# class

I have this JSON string:
[{"fkp_keyword":"CLI_RID"},
{"fkp_keyword":"DOC_NAME"},
{"fkp_keyword":"FILENAME"},
{"fkp_keyword":"PRINT_DATE"},
{"fkp_keyword":"EVENT_CODE"},
{"fkp_keyword":"CONFL_RID"},
{"fkp_keyword":"PROGRAM_CODE"},
{"fkp_keyword":"CES"},
{"fkp_keyword":"DISTR"},
{"fkp_keyword":"REC_DATE"},
{"fkp_keyword":"REC_RID"},
{"fkp_keyword":"PFL_RID"},
{"fkp_keyword":"DES"},
{"fkp_keyword":"CER_RID"}
]
I need to convert it into a List of the class kw below.
Definitions:
public class kw
{
public string fkp_keyword { get; set; }
}
But this code:
List<kw> header = new List<kw>();
using (WebClient client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string result = client.DownloadString(parms);
header = JsonConvert.DeserializeObject<List<kw>>(result);
}
The call returns the JSON string above but when trying to convert it, the code above returns this exception:
Error converting value to type 'System.Collections.Generic.List[LA.Models.kw]
Update
I changed the definitions to this:
public class kwList
{
public kw[] Property1 { get; set; }
}
public class kw
{
public string fkp_keyword { get; set; }
}
and the code to this:
kwList header = new kwList();
using (WebClient client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string result = client.DownloadString(parms);
header = JsonConvert.DeserializeObject<kwList>(result);
}
But now I'm getting this Exception:
Could not cast or convert from System.String to LicenseeArchive.Models.kwList.
What am I doing wrong?
For whatever reason, it appears that the JSON string returned by that URL is double-serialized. That is, it contains extra backslashes to escape all the quotes, which then prevents it from being deserialized properly to an array of objects. That is why you are getting an error.
To work around the problem, you can deserialize it twice: first to unescape the JSON, the second to do the "real" deserialization to your classes. Longer term, you may also wish to contact the provider of the API to see if they will fix their JSON.
List<kw> header = new List<kw>();
using (WebClient client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string result = client.DownloadString(parms);
string unescapedJson = JsonConvert.DeserializeObject<string>(result);
header = JsonConvert.DeserializeObject<List<kw>>(unescapedJson);
}
Fiddle: https://dotnetfiddle.net/XEULdy
JSON string you provided can be loaded with your first class definition:
public class kw
{
public string fkp_keyword { get; set; }
}
Example:
string example = "[{\"fkp_keyword\":\"CLI_RID\"}, {\"fkp_keyword\":\"DOC_NAME\"}, {\"fkp_keyword\":\"FILENAME\"}]";
List<kw> kws = JsonConvert.DeserializeObject<List<kw>>(example);
Maybe you are not providing all details. Or your json string looks different.

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