Get c# object list from response.Content.ReadAsStringAsync() - asp.net

I am wroking on asp.net core web api and I am new in asp.net core. I make a web api and want to call it from web application controller and its works good. My problem is I want to convert json in c# object list. I already get a json format from web api, but enable to convert it into c# object list. I google a lot and find one solution in everywhere and that is
JsonConvert.DeserializeObject<BusinessUnit>(result);
Which is not working for me. My Code :
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync(baseAddress + "/api/BusinessUnit");
var result = response.Content.ReadAsStringAsync();
List<BusinessUnit> businessunits = JsonConvert.DeserializeObject<BusinessUnit>(result); //result shows error because it needs string as parameter.
I am still trying but enable to solve this problem.
How can I convert "result(json format)" in c# object list "businessunits" ?
Thanks in advance.

You need to await the task like so:
var result = await response.Content.ReadAsStringAsync();
Danger of using var, as now it inferred the type as Task<string>. If you had tried:
string result = response.Content.ReadAsStringAsync();
It would have immediately given you an error that it can't cast Task<string> to string.
EDIT: The other error you have is that you are trying to deserialize the JSON into an object when it is actually an array.
List<BusinessUnit> businessunits = JsonConvert.DeserializeObject<List<BusinessUnit>>(result);

In .NET Core this is done as:
var units = await result.Content.ReadFromJsonAsync<List<BusinessUnit>>();

You can use .Result to convert in string :
string XYZ = response.Content.ReadAsStringAsync().Result;

You could try this:
IEnumerable<BusinessUnit> result = await response.Content.ReadAsAsync<IEnumerable<BusinessUnit>>();
Saludos.

Related

How to stop ASP .NET from JSONifying JSON

I am currently trying to wrap an internal API and make it external. To do so, I am trying to relay the JSON responses from the internal API and send that exact response when someone makes a get request. Instead, ASP .NET is JSONifying that son and adding extra back slashes as escape characters (when in fact those slashes are really escape slashes put in by the internal api).
How can i get it so asp does not jsonify the string
You can write your json data directly to response and set right content headers.
public HttpResponseMessage GetData()
{
var json = "\"value\": \"da\\ta\"";
var resp = Request.CreateResponse(HttpStatusCode.OK);
resp.Content = new StringContent(json);
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
resp.Content.Headers.ContentEncoding = //your json encoding, you can get it from response inner API
return resp;
}

Json format of data which is having HTML tags in Web API in C#

I have an object Example
Class Event
{
string country{get;set}
}
Events test = new Evnts();
test.country="<P>India<P>"
How i need to Json format for the above.
I used the method
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
StringContent sc = new StringContent(oSerializer.Serialize(list));
sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return sc;
But this is giving output result as "City": "\u003cp\u003eIndia\u003cp\u003e",
Please comment on this .
Thank you
That's encoded <> tag representation. You shouldn't return specific html element in JSON response. Also, no need to use JavaScriptSerializer class. You can simply return your "Event" class as a result of your svc web api service.
Actually I am fetching Rich text from Sitecore Item,
I used Regex to remove the HTML tags and Replace Method to replace the "’" and Replace(" ",""). I am directly sending the List of events not using JavaScriptSerializer class.
((Regex.Replace(eve["text"].ToString(), "<[^>]*>", "").Replace("’", "'")).Replace(" ","")).Replace("\n","");
Thank you Pravin and Ivan Sivak

How to do an API call in ASP.NET (VB)

I want to make an API call where the response is in XML format.
This is the API description: http://www.dictionaryapi.com/products/api-collegiate-dictionary.htm
I have registered and I have a key to use in the request URL.
Could anyone give me an idea of how to make the call and analyse the response?
Thankyou.
Something along the lines of:
var request = WebRequest.Create("http://www.dictionaryapi.com/api/v1/references/collegiate/xml/hypocrite?key=1234");
var response = request.GetResponse();
var xdoc = XDocument.Load(response.GetResponseStream());
Then you can grab what you need like:
xdoc.Element("ElementName");

"Unexpected list type" exception when invoking ISessionAwareCoreService.GetList()

I am invoking the Tridion 2011 SP1 core service via the shipped client assembly. When I attempt to list the contents of a publication, I get an exception.
The code (simplified) looks like this:
ItemsFilterData filter = new Tridion.ContentManager.CoreService
.Client.RepositoryItemsFilterData.RepositoryItemsFilterData();
filter.ItemTypes = new ItemType[] {
ItemType.Folder,
ItemType.StructureGroup
};
filter.Recursive = false;
IEnumerable<IdentifiableObjectData> childItems = core.GetList("tcm:0-15-1", filter);
Note: the variable "core" refers to an ISessionAwareCoreService which I can successfully use to call, for example core.GetSystemWideList()
When .GetList is invoked, I get the following exception:
System.ServiceModel.FaultException`1 was unhandled
Message=Unexpected list type:
Tridion.ContentManager.Data.ContentManagement.RepositoryItemsFilterData.
What are the possible causes of this problem? Can you suggest a good general approach for interpreting this kind of message?
You can't get the direct children of a Publication using GetList. Instead you should just load the PublicationData with a client.Read and then access the RootFolder and RootStructureGroup on that.
PublicationData pub = (PublicationData)core.Read("tcm:0-1-1", new ReadOptions());
string rootFolder = pub.RootFolder.IdRef;
string rootSG = pub.RootStructureGroup.IdRef;
Alternatively you can call GetListXml with your RepositoryItemsFilterData and extract the items from the XML yourself.
XElement listResult = core.GetListXml(parent.ID, filter);

Parse a JSON query response string in ASP.NET

Hey guys I have the following code working which is sending a GET Request and receiving JSON Response.
Now I can basically go
GetWeatherByLocation(53.3, -6.28);
and the method returns
{"status":"OK","url":"http://www.link.com/areas/rathfarnham-11","name":"Rathfarnham"}
I was now wondering how can I retrieve the values for
URL
Name
from the string returned
THanks a lot
Im using ASP.NET 2 this is my calling code
public static string GetWeatherByLocation(double lat, double lng)
{
string formattedUri = String.Format(CultureInfo.InvariantCulture,
FindNearbyWeatherUrl, lat, lng);
HttpWebRequest webRequest = GetWebRequest(formattedUri);
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
jsonResponse = sr.ReadToEnd();
}
return jsonResponse;
}
Your calling code is in javascript, i guess. Just use the response as a javascript object, because the json format is a notation for a javascript object. You can access its properties directly:
var returningValue = {"status":"OK","url":"http://www.link.com/areas/rathfarnham-11","name":"Rathfarnham"} ;
alert(returningValue.status);
alert(returningValue.url);
alert(returningValue.name);
edit: if you want to parse json in .net you can see this question where somebody explains how to parse the object using JavaScriptSerializer from System.Web.Extensions.dll
edit 2: if your version of .net doesn't let you play with this .dll i'd recommend looking into json.net previous releases, notably the last 2.0 release. But you should have access to the dll since it appeared in .net 2.0, albeit in the AJAX framework if my memory is good...
It's possible to parse your object by hand, but i'd really recommend using a library instead. If you want to do it by hand, you're in a complex world...

Resources