How to send model C# as raw JSON? - c#

I have an data model in C#:
public class RootObjectData
{
public Person person { get; set; }
public Parameters parameters { get; set; }
public Indicators indicators { get; set; }
}
I tried to send this data as raw JSON using RestSharp:
public string send(RootObjectData data) {
var client = new RestClient(RestfulPaths.BASE_URL);
var request = new RestRequest(RestfulPaths.GET_ANALYS, Method.POST);
request.AddJsonBody(data);
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
}
But it send wrong format data.
I fill data like this:
RootObjectData bioModel = new RootObjectData();
bioModel.person = new Person();
bioModel.indicators = new Indicators();
bioModel.parameters = new Parameters();
If to use POSTman a correct data is (raw JSON):
{
"person": {
},
"parameters": {
},
"indicators": {
}
}
I try to attain this sending data object in C#

Related

Sending List in http request in C#

I'm trying to send List (of strings) as http request to a flask python backend but I cant figure how to parse the list into json format to send that
I tryed this:
var myObject = (dynamic)new JsonObject();
myObject.List = new List<string>();
// add items to your list
according to this: C# HTTP post , how to post with List<XX> parameter?
but It's says that List isn't recognized.
any help or other method to do this?
Use JsonSerializer in order to convert any object to a string
var list = new List<string>();
httpClient.PostAsync(
"",
new StringContent(
System.Text.Json.JsonSerializer.Serialize(list),
Encoding.UTF8,
"application/json"));
If you need to send an object with a List property:
var list = new List<string>();
httpClient.PostAsync(
"",
new StringContent(
System.Text.Json.JsonSerializer.Serialize(new {List = list}),
Encoding.UTF8,
"application/json"));
please prefer this Microsoft documentation.
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-7-0
using System.Text.Json;
namespace SerializeToFile
{
public class WeatherForecast
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string? Summary { get; set; }
}
public class Program
{
public static void Main()
{
var weatherForecast = new WeatherForecast
{
Date = DateTime.Parse("2019-08-01"),
TemperatureCelsius = 25,
Summary = "Hot"
};
string fileName = "WeatherForecast.json";
string jsonString = JsonSerializer.Serialize(weatherForecast);
File.WriteAllText(fileName, jsonString);
Console.WriteLine(File.ReadAllText(fileName));
}
}
}
// output:
//{"Date":"2019-08-01T00:00:00-
07:00","TemperatureCelsius":25,"Summary":"Hot"}

Send post data to api in C#

I have this api in php that works ok when sending data from an html form.
<?php
include_once 'apiAppMovil.php';
$api = new AppMovil();
$error = '';
if(isset($_POST["nombre"]) && isset($_POST["ape"]) && isset($_POST["email"]) && isset($_POST["pass"])){
if($api->subirImagen($_FILES['foto'])){
$item = array(
"nombre" => $_POST["nombre"],
"ape" => $_POST["ape"],
"email" => $_POST["email"],
"pass" => $_POST["pass"],
"foto" => $api->getImagen() //Not used
);
$api->add($item);
}else{
$api->error('Error con el archivo: ' . $api->getError());
}
}
else{
$api->error('Error al llamar a la API');
}
?>
I want to send data but from c#. My class is the following:
public partial class Root
{
[JsonProperty("items")]
public Item[] Items { get; set; }
}
public partial class Item
{/*
[JsonProperty("id")]
[JsonConverter(typeof(ParseStringConverter))]
public long Id { get; set; }*/
[JsonProperty("nombre")]
public string Nombre { get; set; }
[JsonProperty("ape")]
public string Ape { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("pass")]
public string Pass { get; set; }
[JsonProperty("foto")] //Not Used
public string Foto { get; set; }
}
and my method is:
private async Task SignUpApiPost()
{
var data = new Item
{
Nombre = "Eric",
Ape = "Pino",
Pass = "M2022",
Email = "ericpinodiaz#gmail.com",
Foto = "default.jpeg" //Not Used
};
// Serialize our concrete class into a JSON String
var json = JsonConvert.SerializeObject(data);
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(json.ToString(), Encoding.UTF8, "application/json");
var httpClient = new HttpClient();
// Do the actual request and await the response
var response = await httpClient.PostAsync("https://app.domainexample.com/rest/add.php", httpContent);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//do thing
}
}
But I can't get the data to arrive, I have the errors "Error al llamar a la API" from Api php.
I think the problem is that var data = new Item{ is not declared correctly, can you help me and tell me where I am going wrong?
Thank you.
Edit:
I add the html with which it works correctly:
You should try something like the one below.
client.BaseAddress = new Uri("your url");
//HTTP POST
var postTask = client.PostAsJsonAsync<StudentViewModel>("your parameter name", Item);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
//do something
}

JSON Not Deserializing

This is one of my first ventures into WCF/JSON. I created a WCF Web Service. This is one of my methods. It is how I serialize the datable to JSON.
public string GetPrayers()
{
DataTable myDt = new DataTable();
myDt = sprocToDT("LoadPrayers");
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(myDt, Formatting.None);
return JSONString;
}
This returns a nice JSON Dataset:
{"GetPrayersResult":"[{\"prayerid\":2,\"prayer\":\"Please pray for my
dog Rusty. He has cancer
:(\",\"prayerCategory\":\"General\",\"prayerDate\":\"2017-06-10T21:24:16.1\",\"handle\":\"GuruJee\",\"country\":\"USA\"},{\"prayerid\":1,\"prayer\":\"Help
Me I need a appendectomy
STAT\",\"prayerCategory\":\"Sports\",\"prayerDate\":\"2017-04-10T20:30:39.77\",\"handle\":\"GuruJee\",\"country\":\"USA\"}]"}
When I go to deserialize it I get all nulls. Here is the classes I created:
public class PrayUpPrayers
{
public string prayer { get; set; }
public string prayerid { get; set; }
public string prayerCategory { get; set; }
public string prayerCategoryID { get; set; }
public string prayerDate { get; set; }
public string handle { get; set; }
public string country { get; set; }
}
public class ThePrayer
{
public PrayUpPrayers prayers { get; set; }
}
}
This is how I am retrieving the JSON:
void getData()
{
var request = HttpWebRequest.Create(string.Format(#"URLGoesHere"));
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
string foo = content.ToString();
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.PrayUpPrayers>(foo,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
Testing is always null? Is the issue that I am serializing it wrong, could it be the class structure, or is it related to how I am deserializing it. One important note: I checked my JSON on one of these JSONClassesFromC# sites and it only returns the GetPrayersResult as the only class item. Ignoring completely my entire structure.
You didn't provide the code for sprocToDT, but it should create ThePrayer object witch should contain list of PrayUpPrayers
public class ThePrayer
{
public List<PrayUpPrayers> prayers { get; set; }
}
And then you should deserialize ThePrayer object, not PrayUpPrayers.
For example
PrayUpPrayers prayUpPrayers1 = new PrayUpPrayers
{
prayer = "Please pray for my dog Rusty. He has cancer",
prayerid = "2",
prayerCategory = "General",
prayerDate = "2017-06-10T21:24:16.1",
handle = "GuruJee",
country = "USA"
};
PrayUpPrayers prayUpPrayers2 = new PrayUpPrayers
{
prayer = "Help Me I need a appendectomy STAT",
prayerid = "1",
prayerCategory = "Sports",
prayerDate = "2017-04-10T20:30:39.77",
handle = "GuruJee",
country = "USA"
};
ThePrayer thePrayer = new ThePrayer
{
prayers = new List<PrayUpPrayers>
{
prayUpPrayers1, prayUpPrayers2
}
};
myDt in your code should be the same as thePrayer instance in my code.
JSONString = JsonConvert.SerializeObject(myDt, Formatting.None);
will provide Json that looks like
"{\"prayers\":[{\"prayer\":\"Please pray for my dog Rusty. He has
cancer\",\"prayerid\":\"2\",\"prayerCategory\":\"General\",\"prayerCategoryID\":null,\"prayerDate\":\"2017-06-10T21:24:16.1\",\"handle\":\"GuruJee\",\"country\":\"USA\"},{\"prayer\":\"Help
Me I need a appendectomy
STAT\",\"prayerid\":\"1\",\"prayerCategory\":\"Sports\",\"prayerCategoryID\":null,\"prayerDate\":\"2017-04-10T20:30:39.77\",\"handle\":\"GuruJee\",\"country\":\"USA\"}]}"
And deserialize will look like
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.ThePrayer>(foo,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
that's simple. you should deserilze the output twice. try this:
var output= DeserializeObject<string>(foo);
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.PrayUpPrayers>(output,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});

Converting list of objects to json array

I have a List of class objects that have email address and status data members. I am trying to convert these to a json, making sure to have the "operations" word on the array.
This is my class:
class MyClass
{
public string email {get; set; }
public string status { get; set; }
}
This is my current code (not building):
List<MyClass> data = new List<MyClass>();
data = MagicallyGetData();
string json = new {
operations = new {
JsonConvert.SerializeObject(data.Select(s => new {
email_address = s.email,
status = s.status
}))
}
};
This is the JSON I am trying to get:
{
"operations": [
{
"email_address": "email1#email.com",
"status": "good2go"
},
{
"email_address": "email2#email.com",
"status": "good2go"
},...
]
}
EDIT1
I should mention that the data I am getting for this comes from a DB. I am de-serializing a JSON from the DB and using the data in several different ways, so I cannot change the member names of my class.
I believe this will give you what you want. You will have to change your class property names if possible.
Given this class
class MyClass
{
public string email_address { get; set; }
public string status { get; set; }
}
You can add the objects to a list
List<MyClass> data = new List<MyClass>()
{
new MyClass(){email_address = "e1#it.io", status = "s1"}
, new MyClass(){ email_address = "e2#it.io", status = "s1"}
};
Using an anonymous-type you can assign data to the property operations
var json = JsonConvert.SerializeObject(new
{
operations = data
});
class MyClass
{
public string email_address { get; set; }
public string status { get; set; }
}
List<MyClass> data = new List<MyClass>() { new MyClass() { email_address = "email1#email.com", status = "good2go" }, new MyClass() { email_address = "email2#email.com", status = "good2go" } };
//Serialize
var json = JsonConvert.SerializeObject(data);
//Deserialize
var jsonToList = JsonConvert.DeserializeObject<List<MyClass>>(json);
You can try with something like this:
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(data);
Here is the simple code
JArray.FromObject(objList);

How to Deserialize JSON in RestSharp?

I am just beginning developing using RestSharp and have hit an early roadblock. I think once I understand this simple, but key, concept, I should be off and running. I need to return an Access Token before making my standard calls later. I have set up the following classes, generated from json2csharp.com:
public class AccessToken
{
public string Instance_Url { get; set; }
public string Token { get; set; }
public string Expiration_date { get; set; }
public string Refresh_Token { get; set; }
}
public class RootObject
{
public AccessToken Access_Token { get; set; }
}
I have coded the following on a button click:
var tokenclient = new RestClient();
tokenclient.BaseUrl = "https://url";
tokenclient.Authenticator = new HttpBasicAuthenticator("username", "password");
var tokenrequest = new RestRequest(Method.GET);
tokenrequest.RequestFormat = DataFormat.Json;
IRestResponse tokenresponse = tokenclient.Execute(tokenrequest);
var content = tokenresponse.Content;
RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer();
var des = deserial.Deserialize<AccessToken>(tokenresponse);
I am able to return the following JSON as a string:
{
"Access_Token": {
"Instance_Url": "https://url",
"Token": "StringToken",
"Expiration_date": "9/30/2015 6:15:27 PM",
"Refresh_Token": "StringToken"
}
}
However, when I pull des.Token, it returns a blank value. Can somebody kindly point out my error?
using Newtonsoft.Json;
var response = client.DownloadString(url + queryString);
ResponseModel<string> dataResponse = new ResponseModel<string>();
if (!string.IsNullOrEmpty(response))
{
dataResponse = JsonConvert.DeserializeObject<ResponseModel<string>>(response);
}

Categories