Creating jira issue via Rest c# httpClient - c#

I have read one answer on atlassian https://answers.atlassian.com/questions/79902/using-httpclient-c-to-create-a-jira-issue-via-rest-generates-bad-request-response where one user created a JIRA issue by the following code. I adapted it but get an error by using a self-build class issue with ObjectContent
Http.HttpContent content = new Http.ObjectContent<Issue>(data, jsonFormatter);
The compiler wont accept it. Does anybody know why?
public string CreateJiraIssue()
{
string data= #"{ ""fields"": {
""project"":
{
""key"": ""HELP""
},
""summary"": ""Test Ticket"",
""description"": ""Creating of an issue using project keys and issue type names using the REST API"",
""issuetype"": {
""name"": ""Ticket""
},
""assignee"": { ""name"": ""user"" }
}
}";
string postUrl = "https://xxx.jira.com/rest/api/2/";
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.BaseAddress = new System.Uri(postUrl);
byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter();
System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent<Issue>(data, jsonFormatter);
System.Net.Http.HttpResponseMessage response = client.PostAsync("issue", content).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
else
{
return response.StatusCode.ToString();
}
And using
namespace IOnotification_System
{
public class Issue
{
public Fields fields { get; set; }
public Issue()
{
fields = new Fields();
}
}
public class Fields
{
public Project project { get; set; }
public string summary { get; set; }
public string description { get; set; }
public Assignee assignee { get; set; }
public IssueType issuetype { get; set; }
public Fields()
{
project = new Project();
issuetype = new IssueType();
}
}
public class Project
{
public string key { get; set; }
}
public class IssueType
{
public string name { get; set; }
}
public class Assignee
{
public string name { get; set; }
}
}

EDIT
The message clearly says that System.Net.Http.ObjectContent() expects an Issue object for its first parameter. I expect there is another message right after that saying that there is no conversion possible from a string to an Issue.
You are passing a string to a method that expects an Issue object. The formatter is used to convert an Issue object to a Json string.
You already have the string, so there is no point in trying to convert it. You only need the formatter if you have an Issue instance which you want to convert to a Json string. You can use the StringContent class and use its Headers property to add any headers not already set on the client, eg:
var content=new StringContent(data);
Original
What is the error message and what kind of project are you using? The System.Net.Http.Formatting namespace is part of ASP.NET Web API. Are you building an ASP.NET application, a console application, something else?
Unless you ARE building an ASP.NET site this code won't work. If your only issue is how to parse Json requests, just use another Json deserialization class. Json.NET is a very popular choice.
In any case there is no reason to use a Json class to convert a string to an HttpContent object containing that exact same string. You can use the StringContent class and use its Headers property to add any headers not already set on the client.

The following does the magic:
var content = new StringContent(data, Encoding.UTF8, "application/json");

Related

C# JSON URL get data

Im new to System.Net with C#
I want a way to get info from this website api: https://fn-api.glitch.me/api/aes
from its json to a C# string
I have this so far
I don't know how to get each item and where to put the url (im really new to this).
I want the url in a string:
public class Data
{
public string build { get; set; }
public string netCL { get; set; }
public string manifestID { get; set; }
public string aes { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
Okay, this is how you get about it. I am showing you an example using HttpClient to first read the content from the API and then de-serialize it using Newtonsoft package.
HttpClient class:
public class HttpClientFactory
{
private string webServiceUrl = "https://fn-api.glitch.me/";
public HttpClient CreateClient()
{
var client = new HttpClient();
SetupClientDefaults(client);
return client;
}
protected virtual void SetupClientDefaults(HttpClient client)
{
//This is global for all REST web service calls
client.Timeout = TimeSpan.FromSeconds(60);
client.BaseAddress = new Uri(webServiceUrl);
}
}
Your Model class:
public class Data
{
public string build { get; set; }
public string netCL { get; set; }
public string manifestID { get; set; }
public string aes { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
Now, you can call this class and create an instance of the HttpClient like this:
public RootObject InvokeAPI()
{
RootObject apiresponse = new RootObject();
string result = string.Empty;
HttpClientFactory clientFactory = new HttpClientFactory();
var client = clientFactory.CreateClient();
HttpResponseMessage response = client.GetAsync("api/aes").Result;
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
apiresponse = JsonConvert.DeserializeObject<RootObject>(result);
}
return apiresponse;
}
Hope this helps you out.
EDIT:
As per your code, you need to call the API on your Button click:
private void metroButton2_Click_1(object sender, EventArgs e)
{
//You need to invoke the API method !!!!
var apiresponse=InvokeAPI();
metroTextBox1.Text = apiresponse.data.aes;
}
Be sure to put try-catch blocks on your code for error handling.
I'd recommend using a 3rd party library like RestSharp. It'll give you a client that's easy to work with and does the converting into objects automatically.
Alternatively you could use the WebClient and download the JSON. Using something like Json.NET allows you to deserialize the JSON into an object.
Easiest way to read from a URL into a string in .NET
I use JSON.Net.

How to deserialize WebAPI string response which has doubles quotes content for some column

By using below code i am calling api and trying to deserialize. I have replaced string to json format as like below,
//Code to get string response from api
var client = new WebClient();
client.Credentials = new NetworkCredential(userName, passWord);
client.Headers.Add(headerKey, headerValue);
client.QueryString.Add("companynumber", companyNumber);
var response = client.DownloadString(customerAPI);
response = response.Replace("\"", "").Replace("\\", "\"");
var results = JsonConvert.DeserializeObject<List<ProjectResponse>>(response);
output json result
"\"[{\\"data\\":{\\"closed\\":false,\\"companynumber\\":\\"430\\",\\"customernumber\\":\\"430\\\\"INTERNAL\\"}},{\\"data\\":{\\"closed\\":false,\\"companynumber\\":\\"430\\",\\"customernumber\\":\\"430INTERNAL\\"}}]"
And the respective deserialize class is below,
public class Project
{
public Nullable<long> CompanyNumber { get; set; }
public string CustomerNumber { get; set; }
public bool Closed { get; set; }
}
public class ProjectResponse
{
public Project data { get; set; }
}
In this example i am getting two list, in the first one customernumber has \\"430\\\\"INTERNAL\\ double quotes and backslash value so this is not allowing me deserialize to my respective class.so how to deserialize string eventhough one of the column has double quotes in it.
The code has be serialized twice. A model was serialized to JSON and then the JSON string was serialized again.
To fix you need to do the reverse.
var response = client.DownloadString(customerAPI);
var json = JsonConver.DeserializeObject<string>(response);
var projects = JsonConvert.SeseializeObject<List<ProjectResponse>>(json);

Caching and Parsing etag with HttpClient and Odatav4(Etag always null in Httpclient)

The case : I'm Using EF6 and WebApi controls to store my result
public class Profile
{
public string ZipFile { get; set; } // input parameter
[ConcurrencyCheck]
public Guid Id { get; set; } // output parameter generated by Web API
public string Name { get; set; } // output parameter from Profile XML file
public string Description { get; set; } // output parameter from Profile XML file}
So i'm using ConcurrencyCheck to generate etag with odataV4
When i'm reading the get result with post man i getting :
As you see the etage there
The problem : in my client i use HttpClient as follows
public static string GetAsJsonAsync(string route)
{
string result = string.Empty;
try
{
var fullRoute = PrepareHttpRequest(route);
var client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(fullRoute).Result)
{
result = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
}
}
catch (Exception ex)
{
throw new HttpRequestException(result, ex);
}
return result;
}
the response header if-match and etag are always ,I have no idea how to parse the "#odata.etg" value,
so my question is how i parsing the etag value and store it?
For future references the solution is Attach to your model [JsonProperty("#odata.etag")]

Good but easy method of deserializing JSON data in c#

I've been struggling for quite a while, but now I managed to successfully pull JSON data from a web API.
My code so far (only a test snippet thus far):
var url = "http://www.trola.si/bavarski";
string text;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
var json = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(json.GetResponseStream()))
{
text = sr.ReadToEnd();
}
As far as pulling data goes, this is ok, right?
Well here's where it gets a bit confusing. There are a lot resources online and all of them differ quite a bit. Do I need to create a class that will hold the data and { get; set; } too?
Would RESTsharp or Json.NET make my job easier? Any suggestions are appreciated.
You do not need any third party JSON libs.
Get the data to a string. You have already done this.
Create your data classes. I like igrali's idea of using Visual Studio to do it. But if the data is simple just write the class yourself:
[DataContract]
public class PersonInfo
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
Deserialize from the string to the classes:
I like to use this generic helper:
public static T Deserialize<T>(string json)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T obj = (T)serializer.ReadObject(stream);
return obj;
}
}
And then call it like this:
PersonInfo info = (PersonInfo)JsonHelper.Deserialize<PersonInfo>(s);
First of all, you will want to create classes that represent the JSON model you received. There's more than one way to do it - you can use json2csharp or even better, the Visual Studio feature called Paste JSON As Classes (find it in: Edit -> Paste Special -> Paste JSON As Classes).
Once you have the classes, you can use Json.NET to help you with the JSON response. You probably want to deserialize the string (JSON) you received to C# objects. To do it, you can just call the JsonConvert.DeserializeObject method.
var myObject = JsonConvert.DeserializeObject<MyClass>(json);
where MyClass is any kind of type you are deserializing to.
There's a WebApi client that will take care of all of the serialization for you.
http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
Here's a sample:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// New code:
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
}
Json.net helps a lot with this. You can deserialize to anonymous types or POCO objects. I hope below solution helps you get started.
async Task Main()
{
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage())
{
request.RequestUri = new Uri("http://www.trola.si/bavarski");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Method = HttpMethod.Get;
var result = await client.SendAsync(request);
string jsonStr = await result.Content.ReadAsStringAsync();
Result obj = JsonConvert.DeserializeObject<Result>(jsonStr);
obj.Dump();
}
}
}
// Define other methods and classes here
public class Result
{
[JsonProperty(PropertyName = "stations")]
public Station[] Stations { get; set;}
}
public class Station
{
[JsonProperty(PropertyName = "number")]
public string Number { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "buses")]
public Bus[] Buses { get; set; }
}
public class Bus
{
[JsonProperty(PropertyName = "direction")]
public string Direction { get; set; }
[JsonProperty(PropertyName = "number")]
public string Number { get; set; }
[JsonProperty(PropertyName = "arrivals")]
public int[] Arrivals { get; set; }
}

Json Deserialize C# Class

Im new to Json and so i need your help to deserialize something.
I have a httpclient sending a webrequest:
HttpClient http = new HttpClient();
HttpResponseMessage response = await http.GetAsync(JsonBaseuri + IDInput.Text.ToString());
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
InventoryJsonData.RootObject root1 = new InventoryJsonData.RootObject();
root1 = JsonConvert.DeserializeObject<InventoryJsonData.RootObject>(content);
The RootClass is defined as:
class InventoryJsonData
{
public class RootObject
{
public bool Success { get; set; }
public object Error { get; set; }
public double Price { get; set; }
public string Username { get; set; }
}
}
I get an error and i dont know if my code is right for what i want to do. I want to get a root1 object with the Attributes from the Json data from the webrequest. What did i do wrong?
Similar exception occur when use VS2015 and Newtonsoft.Json 7.0 version. If you use version 7 of serializer maybe just try downgrade it to v6. Use nuget to change version

Categories

Resources