Fetching json array, null pointer refrence exception - json

{"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

Related

Post data to A URL by C#

How can I Post for example this information of below to this website "http://restapi.adequateshop.com/api/Tourist"
by C# code?
tourist_name: "dummy"
tourist_email: "test123#test.com"
tourist_location: "Paris"
static void Main(string[] args)
{
//create the constructor with post type and few data
string data = "tourist_name=Mike&tourist_email=miked123#gmail.com&tourist_location=Paris";
MyWebRequest myRequest = new MyWebRequest("http://restapi.adequateshop.com/api/Tourist", "POST", data);
//show the response string on the console screen.
string Response = myRequest.GetResponse();
}
You can put your data in a new class :
class RequestData
{
string tourist_name { get; set; }
string tourist_email { get; set; }
string tourist_location { get; set; }
}
Then you can serialize your object to JSON:
RequestData requestData = new RequestData();
requestData.tourist_name ="Mike";
requestData.tourist_email ="miked123#gmail.com";
requestData.tourist_location ="Paris";
string jsonData = JsonConvert.SerializeObject(requestData);
Then send your JSON to API
string URL="http://restapi.adequateshop.com/api/Tourist";
var jsonContent = new StringContent(jsonData,Encoding.UTF8,"application/json");
var result = client.PostAsync(URL,jsonContent).Result;
I hope this answers your question.

Xamarin Forms reading JSON

So I am retrieving JSON data from my site and this is my code:
The model:
class Reservations
{
public string id_reservation { get; set; }
public string spz { get; set; }
public string reservation_day { get; set; }
public string reservation_time { get; set; }
public string ip_address { get; set; }
}
The connection and parsing:
protected async void CheckReservations(string day)
{
if (CrossConnectivity.Current.IsConnected)
{
try
{
private const string Url = "Urltomysite";
private HttpClient _client = new HttpClient();
var content = await _client.GetStringAsync(Url);
List<Reservations> myData = JsonConvert.DeserializeObject<List<Reservations>>(content);
foreach (Reservations res in myData)
{
System.Console.WriteLine("Time:" + res.reservation_time);
}
}
catch (Exception e)
{
Debug.WriteLine("" + e);
}
}
}
And the JSON response from my site:
[
{
id_reservation: "39",
spz: "NRGH67L",
reservation_day: "2019-01-26",
reservation_time: "14:00",
ip_address: "192.168.137.5"
}
]
But when I try to print the reservation_time from List of the Object in the foreach I dont get any results. I am still pretty new to this and got this far from tutorials, so dont know what I am missing.
Thanx for any replies.
I suggest using a crash prone way of this
var response = await client.GetAsync(uri);
if(response.IsSuccessStatusCode)
{
var json = await responseMessage.Content.ReadAsStringAsync(); //using ReadAsStreamAsync() gives you better performance
List<Reservations> myData = JsonConvert.DeserializeObject<List<Reservations>>(json);
//do the rest jobs
}
else
{
//alert the api call failed
}

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);
}
}
}
}

Xamarin store multiple data in Variable

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

Sending data by JSON

I want to send JSON from desktop application to the server with mvc wepApi.
this is my desktop application code ,that convert data to the JSON and send it.
private void btnAddUserType_Click(object sender, EventArgs e)
{
UserType userType = new UserType();
userType.UserTypeName = txtUserTypeName.Text;
string json = JsonConvert.SerializeObject(userType);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3852/api/default1");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
streamWriter.Write(json);
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var responseText = streamReader.ReadToEnd();
}
and this is my web api
// POST api/default1
public void Post([FromBody]string value)
{
UserTypeRepository bl = new UserTypeRepository();
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(UserType));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(value));
UserType u = new UserType();
u = (UserType)js.ReadObject(stream);
bl.Add(u);
}
but when post api is calling the Value is null.
why?
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
streamWriter.Write(json);
You are not flushing nor closing the stream, so basically the data never gets to the api.
My code:
Program.cs - Console App
class Program
{
static void Main(string[] args)
{
var user = new UserModel {Id = 4, FirstName = "Michael", LastName = "Angelo"};
var json = JsonConvert.SerializeObject(user);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:56506/api/Values/");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
streamWriter.Write(json);
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
Console.ReadKey();
}
}
UserModel.cs - some data class
public class UserModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Id { get; set; }
}
ValuesController.cs - WebApi controller from template
public class ValuesController : ApiController
{
// GET api/values
public UserModel[] Get()
{
return UserProvider.Instance.Get(); // returns some test data
}
// GET api/values/5
public UserModel Get(int id)
{
return new UserModel{Id=1,FirstName="John",LastName="Smith"};
}
// POST api/values
public void Post([FromBody]UserModel value)
{
if (value == null) // BREAKPOINT HERE, just to see what's in value
{
var x = value;
}
}
}
WebApiConfig.cs - default config with added line about Json, but IT WORKS WITHOUT IT -it's so that I can test GET easily in browser etc. ;)
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Result: