Xamarin store multiple data in Variable - json

I have my code, where i fetch data from a url and parse that data with json.
public async void GetItems()
{
HttpResponseMessage response = new HttpResponseMessage();
HttpClient httpclient = new HttpClient();
Uri uri = new Uri("URL");
response = await httpclient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var JsonContent = await response.Content.ReadAsStringAsync();
JArray jArray = JArray.Parse(JsonContent);
foreach (var data in jArray)
{
var latitude = data["latitude"];
Console.WriteLine(latitude);
}
}
}
in this code I get all my data and print them into the console.
I have a class with the variables i want to set
public class FetchedObjects
{
public string name { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
}
How can I store each data from my jArray into these variables? I want to have access to these from my ios or android project.
EDIT
I have some values in json, which are null. How can i handle these, while creating the list? My App crashes, it says :
Error setting value to 'valuename' on 'App.FetchedObjects'

Try it code:
List<FetchedObjects> list = jArray.ToObject<List<FetchedObjects>>();
Edit
in pcl library create class:
public class YourClass
{
public async Task<List<FetchedObjects>> GetItems()
{
....
if(jArray != null)
{
List<FetchedObjects> list = jArray.ToObject<List<FetchedObjects>>();
return list;
}
else
{
return null;
}
...
}
Add reference to pcl library in your ios and android projects and Use class YourClass

Related

Multipart/form-data images upload with JSON asp.net core api

How to POST both images and JSON at the same time in a single POST ? (using multipart)
I have a form with some data that i put into JSON and the users can add 0 to 6 photos and submit it to the API.
Can someone explain me how to do it ?
Edit :
Here is my code thanks to your help :
// POST api/<controller>
[HttpPost, Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public IActionResult Post(ViewModel vm)
{
IActionResult response = Unauthorized();
var data = vm.FamilleProduit;
var reforigine = vm.RefOrigine;
if (vm.Images != null)
{
foreach (var image in vm.Images)
{
byte[] fileData = null;
// read file to byte array
using (var binaryReader = new BinaryReader(image.OpenReadStream()))
{
fileData = binaryReader.ReadBytes((int)image.Length);
}
}
}
return response;
}
public class ViewModel
{
public string FamilleProduit { get; set; }
public string RefOrigine { get; set; }
public List<IFormFile> Images { get; set; }
}
I'm testing with Postman and i POST 2 text (FamilleProduit & RefOrigine) and 2 files (2 images) with "multipart/form-data".
I get the 2 texts perfectly but Images field is null everytime.
Thanks,
Tristan.
You can use built-in class IFormFile to easily work with file upload. To use it together with JSON you may create custom model binder and combine it together in DTO object:
public class ViewModel
{
[ModelBinder(BinderType = typeof(FormDataJsonBinder))]
public DataModel Data { get;set; }
public List<IFormFile> Images { get; set; }
}
public class FormDataJsonBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if(bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
string fieldName = bindingContext.FieldName;
var valueProviderResult = bindingContext.ValueProvider.GetValue(fieldName);
if(valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
else
{
bindingContext.ModelState.SetModelValue(fieldName, valueProviderResult);
}
string value = valueProviderResult.FirstValue;
if(string.IsNullOrEmpty(value))
{
return Task.CompletedTask;
}
try
{
object result = JsonConvert.DeserializeObject(value, bindingContext.ModelType);
bindingContext.Result = ModelBindingResult.Success(result);
}
catch(JsonException)
{
bindingContext.Result = ModelBindingResult.Failed();
}
return Task.CompletedTask;
}
}
Then you can work with it in your controller:
[HttpPost]
public IActionResult Create(ViewModel vm)
{
var data = vm.Data;
if (vm.Images != null)
{
foreach(var image in vm.Images)
{
byte[] fileData = null;
// read file to byte array
using (var binaryReader = new BinaryReader(image.OpenReadStream()))
{
fileData = binaryReader.ReadBytes((int)image.Length);
}
}
}
}

how to get json data from external rest full web service in asp.net mvc 4

I am trying to get the json data from an external rest url(http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3) and display it on my web page in my asp.net mvc application. For that I have written some code i.e.
Controleer---
namespace MyMVCApplication.Controllers
{
public class EmployeeController : Controller
{
string Baseurl = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3";
public async Task<ActionResult> StateDetails()
{
List<State> listStateInfo = new List<State>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await client.GetAsync(Baseurl);
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var StateResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
listStateInfo = JsonConvert.DeserializeObject<List<State>>(StateResponse);
}
return View(listStateInfo);
}
}
}
}
Model----
namespace MyMVCApplication.Models
{
public class State
{
public int ObjectID { get; set; }
public string StateName { get; set; }
public int Black { get; set; }
public int Population { get; set; }
}
}
While debugging the code getting the error: "Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 10, position 1" at
JsonConvert.DeserializeObject.
Please suggest me how to solve this issue.
Replace your url with http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3?f=pjson to get the json version of the web service

MVC 5 populate a model with Json

I have the following ActionResult:
public ActionResult WeatherWidget()
{
string json = string.Empty;
using (var client = new WebClient())
{
json = client.DownloadString("http://api.wunderground.com/api/xxxxxxxxx/geolookup/conditions/forecast/q/Australia/sydney.json");
}
WeatherWidget weatherWidget = new WeatherWidget()
{
//What do I put in here?
};
return View(weatherWidget);
}
And the following model:
public class WeatherWidget
{
public string city { get; set; }
public string lat { get; set; }
public string lon { get; set; }
}
Here is a snippet of the json:
{
"response": {
"version":"0.1",
"termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"geolookup": 1
,
"conditions": 1
,
"forecast": 1
}
}
,"location": {
"type":"INTLCITY",
"country":"AU",
"country_iso3166":"AU",
"country_name":"Australia",
"state":"VC",
"city":"Falls Creek",
"tz_short":"AEST",
"tz_long":"Australia/Melbourne",
"lat":"-36.86999893",
"lon":"147.27000427",
"zip":"00000",
How do I populate the model to display in my view?
e.g.. #Model.city or #Html.Raw(Model.city)
I have no problem displaying the data via Javascript in my view and I can do this with XML and Html using the HtmlAgilityPack, I just can't work out how to do it with Json.
Add Newtonsoft.Json via NuGet, add the following using statements
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
and then use the following code to extract the data out of your JSON response.
JObject parsedJson = (JObject)JsonConvert.DeserializeObject(json);
JObject location = (JObject)parsedJson["location"];
WeatherWidget weatherWidget = new WeatherWidget();
weatherWidget.city = location["city"];
weatherWidget.lat = location["lat"];
weatherWidget.lon = location["lon"];

Fetching json array, null pointer refrence exception

{"names":["name1","name2","name3","name4"]}
I need to fetch this and show them in a list. What I am doing is
public class brand
{ public string Name
{ get; set; }
}
public class brands
{ public list<brand> Names
{ get; set; }
}
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
getdata();
}
private void getdata()
{
string uri = "URL";
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(new Uri(uri));
req.BeginGetResponse(new AsyncCallback(show), req);
}
private void show(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
StreamReader stream1 = new StreamReader(response.GetResponseStream());
string s1 = stream1.ReadToEnd();
var ser = new DataContractJsonSerializer(typeof(brands));
var stream = new MemoryStream(Encoding.Unicode.GetBytes(s1));
var bb = (brands)ser.ReadObject(stream);
foreach (var ev in bb.Names)
{
textBlock1.Text = ev.Name.ToString();
}
}
This I made after reading blog posts. I am getting NullReferenceException.
Please tell me where I am doing wrong or alternative way to do the same.
First learn how to parse your JSON data. Consider this as a json string.
String jsonData = #"{""names"":[""name1"",""name2"",""name3"",""name4""]}";
var brands = JsonConvert.DeserializeObject<Brands>(jsonData);
foreach (var item in brands.names)
{
Console.WriteLine(item);
}
Where your Brands class is like this
public class Brands
{
public List<string> names { get; set; }
}
This above code explains how to parse your json data. Now, coming to fetching your json data from web service, as your request is not a POST request (it appears to be get from your code), you can use a simple WebCleint.
void getData()
{
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri("url"));
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var brands = JsonConvert.DeserializeObject<Brands>(e.Result);
foreach (var item in brands.names)
{
Console.WriteLine(item);
}
}
Check this blog for any other doubts : Parsing JSON in a Windows Phone Application

get Facebook Pages in Windows Phone 7 using C# SDK

I tried to figure this out using the Windows Phone sample from the Facebook C# SDK page, but have been unsuccessful.
Here's the main code:
private void GetPages()
{
var fb = new FacebookClient(_accessToken);
fb.GetCompleted += (o, e) =>
{
if (e.Error != null)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message));
return;
}
var result = (IDictionary<string, object>)e.GetResultData();
// returns data and paging from Facebook
Dispatcher.BeginInvoke(() =>
{
foreach (var item in result)
{
// Not sure if/how to use the custom classes here
//item has .Key and .Value
//.Key = data and .Value contains the key/value pais for each of the pages returned
}
});
};
fb.GetAsync("me/accounts");
}
// Custom Classes
public class FacebookPageCollection
{
[JsonProperty(PropertyName = "data")]
public FacebookPage[] data { get; set; }
[JsonProperty(PropertyName = "paging")]
public FacebookPagePaging paging { get; set; }
}
public class FacebookPage
{
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "access_token")]
public string AccessToken { get; set; }
[JsonProperty(PropertyName = "category")]
public string Category { get; set; }
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
}
public class FacebookPagePaging
{
[JsonProperty(PropertyName = "previous")]
public Uri previous { get; set; }
[JsonProperty(PropertyName = "next")]
public Uri next { get; set; }
}
This is what the variable "result" returns:
{"data":[{"name":"value1","access_token":"value2","category":"value3","id":"value4","perms":["ADMINISTER","EDIT_PROFILE","CREATE_CONTENT","MODERATE_CONTENT","CREATE_ADS","BASIC_ADMIN"]},{"name":"value1","access_token":"value2","category":"value3","id":"value4","perms":["ADMINISTER","EDIT_PROFILE","CREATE_CONTENT","MODERATE_CONTENT","CREATE_ADS","BASIC_ADMIN"]}],"paging":{"next":"url"}}
What I'd like to do is retrieve and save details for each page.
I have been trying to figure this out and have looked over a number of other posts on here and elsewhere. I just don't have enough experience to figure it out.
Any help is appreciated.
Thank you.
Sri
Here is a trick to understanding how to work with json response in fb c# sdk.
Here is the mapping between Javascript JSON and C# JSON. (Notice there is no DateTime and another complex .net objects as it is not part of the JSON spec found in JSON.org)
JsonObject => keyvalue pairs => IDictionary<string, object> / IDictinary<string, dynamic>
JsonArray => array => IList<object> / IList<dynamic>
string => string
number => long/decimal
boolean => bool
Here is how you do the actual mapping.
var result = (IDictionary<string, object>)e.GetResultData();
var data = (IList<object>)result["data"];
foreach(var act in data) {
var account = (IDictionary<string,object>) act;
var name = (string)account["name"];
var accessToken = (string)account["access_token"];
var id = (string)account["id"];
// normalize to IList<string> permissions, so it is easier to work without casting.
var permissions = ((IList<object>)account["perms"]).Select(x => (string)x).ToList();
}