I do have a hard code json,I have to send that in http request using post,
This is the json
{
"RequestHeader": {
"UserName": " ",
"Password": " "
},
"RequestBody": {
"ChannelType": 1,
"BillAccountNumber": "1075-001",
"BillAccountType": null,
"PaymentAmount": 15.05,
"FeeAmount": 3.50,
"ABA": "111993776",
"BankAccount": "1234567899",
"EmailAddress": "jonah#doe.org",
"AccountHolder": "JonahDoe",
"WaiveFee": false,
"Recurring": false,
"CustomData": null
}
}
When i am passing this i am getting the right response
But when i am using the other it is not giving the response what i need, The only difference in first one my hard coded have \r\n and the 2nd one below don't have.
{
"RequestHeader": {
"UserName": " ",
"Password": " "
},
"RequestBody": {
"ChannelType": 1,
"BillAccountNumber": "1075-001",
"BillAccountType": null,
"PaymentAmount": 15.05,
"FeeAmount": 3.5,
"ABA": "111993776",
"BankAccount": "1234567899",
"EmailAddress": "jonah#doe.org",
"AccountHolder": "Jonah Doe",
"WaiveFee": false,
"Recurring": false,
"CustomData": null
}
}
Can some body tell me what is the problem.
Code IS:
class Program
{
static void Main(string[] args)
{
var RequestBody = new RequestBody
{
ChannelType = 1,
BillAccountNumber = "1075-001",
BillAccountType = null,
PaymentAmount = 15.05,
FeeAmount = 3.50,
ABA = "111993776",
BankAccount = "1234567899",
EmailAddress = "jonah#doe.org",
AccountHolder = "Jonah Doe",
WaiveFee = false,
Recurring = false,
CustomData = null
};
var RequestHeader = new RequestHeader
{
UserName = "myUname",
Password = "MyPass"
};
var Request = new Request
{
RequestBody = RequestBody,
RequestHeader = RequestHeader,
};
var ApiCredentials = new ApiCredentials
{
Request = Request
};
var httpWReq = (HttpWebRequest)WebRequest.Create("https://gw1.cwplab.com/api/Gateway/AuthorizeCheck");
httpWReq.ContentType = "application/json";
//httpWReq.Credentials = new NetworkCredential(" ", " ");
string data = "{\r\n\"RequestHeader\":{\r\n\"UserName\":\" \",\r\n\"Password\":\" \"\r\n},\r\n\"RequestBody\":{\r\n \"ChannelType\":1,\r\n \"BillAccountNumber\":\"1075-001\",\r\n \"BillAccountType\":null,\r\n \"PaymentAmount\":15.05,\r\n \"FeeAmount\":3.50,\r\n \"ABA\":\"111993776\",\r\n \"BankAccount\":\"1234567899\",\r\n \"EmailAddress\":\"jonah#doe.org\",\r\n \"AccountHolder\":\"Jonah Doe\",\r\n \"WaiveFee\":false,\r\n \"Recurring\":false,\r\n \"CustomData\":null\r\n}\r\n}\r\n";//Request.ToJSON();
string data1 = Newtonsoft.Json.JsonConvert.SerializeObject(Request);
httpWReq.ContentLength = data.Length;
httpWReq.Method = "POST";
using (StreamWriter stream = new StreamWriter(httpWReq.GetRequestStream()))
{
stream.Write(data);
//stream.Flush();
//stream.Close();
};
dynamic httpResponse = (HttpWebResponse)httpWReq.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
Console.ReadKey();
}
}
}
There is a difference in the JSON. I suspect your server doesn't accept the second json (you say you get the wrong response). \r\n are not mandatory, it is just for the reader.
"FeeAmount": 3.5,
"FeeAmount": 3.50,
And
"AccountHolder": "Jonah Doe",
"AccountHolder": "JonahDoe",
Related
I'm trying to create a workitem via API, but im getting the following error:
{
"innerException": null,
"message": "You must pass a valid patch document in the body of the request.",
"typeName": "Microsoft.VisualStudio.Services.Common.VssPropertyValidationException, Microsoft.VisualStudio.Services.Common",
"typeKey": "VssPropertyValidationException",
"errorCode": 0,
"eventId": 3000
}
Code:
public class Chamados
{
public async Task<string> CriaChamadoDevOps()
{
string organizacao = "xxx";
string departamento = "xxx";
string tipoWorkItem = "xxx";
string authToken = "xxx";
// Montando a Requisição
string urlReq = "https://dev.azure.com/" + organizacao + "/" + departamento + "/_apis/wit/workitems/$" + tipoWorkItem + "?api-version=6.0";
var client = new RestClient(urlReq);
var request = new RestRequest(urlReq, Method.Post);
// Montando Headers
request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "", authToken))));
request.AddHeader("Content-Type", "application/json-patch+json; charset=utf-8");
var body = new JArray {
new JObject {
{ "op", "add" },
{ "path", "/fields/System.Title" },
{ "value", "Assunto Teste" }
},
new JObject {
{ "op", "add" },
{ "path", "/fields/System.State" },
{ "value", "To do" }
},
new JObject {
{ "op", "add" },
{ "path", "/fields/System.Description" },
{ "value", "Descricao Teste" }
},
};
//request.AddBody(body);
request.AddParameter("application/json-patch+json; charset=utf-8", body, ParameterType.RequestBody);
Console.WriteLine(body);
RestResponse response = await client.ExecuteAsync(request);
dynamic resposta = JsonConvert.DeserializeObject(response.Content);
return resposta.ToString();
}
}
When i test it via Postman, it works.
This is how im sending the body to the request:
(Output from Console.WriteLine(body);)
[
{
"op": "add",
"path": "/fields/System.Title",
"value": "Assunto Teste"
},
{
"op": "add",
"path": "/fields/System.State",
"value": "To do"
},
{
"op": "add",
"path": "/fields/System.Description",
"value": "Descricao Teste"
}
]
And i've also tried replacing the "request.AddParameter()" with "request.AddBody()" method.
Maybe you can start by reading the docs: https://restsharp.dev/usage.html#request-body
Then, you'd figure out that since you don't want to build strongly-typed request models and prefer using JObject, you need to handle the serialization yourself:
request.AddStringBody(body.ToString(), "application/json-patch+json");
and that the docs tell you not to add content-type as the request header as it's the content header, and AddStringBody will do it.
I am trying to convert the c# code below to VB. The code goes to a web page, and reads a series of text records. The content of the web response is posted below the code. This piece of code is supposed to read the query results.
//Post request example version 2.0
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.bls.gov/publicAPI/v2/timeseries/data/");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
//Using Javascript Serializer
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var jS = new JavaScriptSerializer();
var newJson = jS.Serialize(new SeriesPost()
{
seriesid = (new List() { "CUUR0000SA0" }).ToArray(),
startyear = "",
endyear = "",
catalog = true,
calculations = true,
annualaverage = true,
registrationKey = "EnterRegistrationKeyHere"
});
//View the JSON output
System.Diagnostics.Debug.WriteLine(newJson);
streamWriter.Write(newJson);
streamWriter.Flush();
streamWriter.Close();
}
The results for the series ID should look like:
"series": [
{
"seriesID": "LAUCN040010000000005",
"data": [
{
"year": "2013",
"period": "M11",
"periodName": "November",
"value": "16393",
"footnotes": [
{
"code": "P",
"text": "Preliminary."
}
]
},
{
"year": "2013",
"period": "M10",
"periodName": "October",
"value": "16536",
"footnotes": [
{
...
}
]
}
]
So far, I've got the code below.
Dim streamWriter As System.IO.StreamWriter
streamWriter = New System.IO.StreamWriter(httpWebRequest.GetRequestStream())
Dim jS As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim SeriesPost() As Array
SeriesPost = New SeriesPost() With {.seriesid = (New List() {"CUUR0000SA0"}).ToArray(),
.startyear = "",
.endyear = "",
.catalog = True,
.calculations = True,
.annualaverage = True,
.registrationKey = "EnterRegistrationKeyHere"
}
Dim newJson As String
newJson = jS.Serialize(loSeriesPost)
' //View the JSON output
System.Diagnostics.Debug.WriteLine(newJson)
streamWriter.Write(newJson)
streamWriter.Flush()
streamWriter.Close()
I can't figure out how to initialize SeriesPost and how to convert this initialization to VB.
Please advise.
Thank you.
Alexander
Try this:
Dim httpWebRequest = CType(WebRequest.Create("https://api.bls.gov/publicAPI/v2/timeseries/data/"), HttpWebRequest)
httpWebRequest.ContentType = "application/json"
httpWebRequest.Method = "POST"
Using streamWriter = New StreamWriter(httpWebRequest.GetRequestStream())
Dim jS = New JavaScriptSerializer()
Dim newJson = jS.Serialize(New SeriesPost() With {
.seriesid = (New List() From {
"CUUR0000SA0"
}).ToArray(),
.startyear = "",
.endyear = "",
.catalog = True,
.calculations = True,
.annualaverage = True,
.registrationKey = "EnterRegistrationKeyHere"
})
System.Diagnostics.Debug.WriteLine(newJson)
streamWriter.Write(newJson)
streamWriter.Flush()
streamWriter.Close()
End Using
I am Serializing data from SQL database to JSON, how can I serialize just the values without the string name OR a function to trim the serialized JSON before Deserializing.
I read about ScriptIgnoreAttribute but didn't see how to relate it with what I want to do
Original JSON
[
{
"CODE": "AF",
"TOTALVALUE": "$23,554,857.27"
},
{
"CODE": "AS",
"TOTALVALUE": "$38,379,964.65"
},
{
"CODE": "SG",
"TOTALVALUE": "$24,134,283.47"
}
]
Desired JSON
[
{
"AF": "$23,554,857.27"
},
{
"AS": "$38,379,964.65"
},
{
"SG": "$24,134,283.47"
}
]
SQL View structure
My SQL query to return the data
SELECT [CODE],[TOTALVALUE] FROM [dbo].[vw_BuyersByCountryValue]
enter code here
Code for Serializing in ASP.NET
[WebMethod]
public void GetBuyersByCountryValue()
{
using (PMMCEntities ctx = new PMMCEntities())
{
ctx.Configuration.ProxyCreationEnabled = false;
var qry = ctx.vw_BuyersByCountryValue.ToList();
var js = new JavaScriptSerializer();
string strResponse = js.Serialize(qry);
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.AddHeader("content-length", strResponse.Length.ToString(CultureInfo.InvariantCulture));
Context.Response.Flush();
Context.Response.Write(strResponse);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
It is very simple
// data from the query
// SELECT CODE, TOTALVALUE FROM vw_BuyersByCountryValue
var sqldata = new []
{
new { Code = "AF", TotalValue = "$23,554,857.27" },
new { Code = "AS", TotalValue = "$38,379,964.65" },
new { Code = "SG", TotalValue = "$24,134,283.47" },
};
var mappeddata = sqldata.Select( r =>
{
var dict = new Dictionary<string,string>();
dict[r.Code] = r.TotalValue;
return dict;
});
var json = JsonConvert.SerializeObject(mappeddata,Formatting.Indented);
content of json
[
{
"AF": "$23,554,857.27"
},
{
"AS": "$38,379,964.65"
},
{
"SG": "$24,134,283.47"
}
]
.net fiddle sample
You can even populate it as
{
"AF": "$23,554,857.27",
"AS": "$38,379,964.65",
"SG": "$24,134,283.47"
}
with
var sqldata = new []
{
new { Code = "AF", TotalValue = "$23,554,857.27" },
new { Code = "AS", TotalValue = "$38,379,964.65" },
new { Code = "SG", TotalValue = "$24,134,283.47" },
};
var mappeddata = sqldata.ToDictionary(r => r.Code, r => r.TotalValue);
var json = JsonConvert.SerializeObject(mappeddata,Formatting.Indented);
.net fiddle sample
Update
[WebMethod]
public void GetBuyersByCountryValue()
{
using (PMMCEntities ctx = new PMMCEntities())
{
ctx.Configuration.ProxyCreationEnabled = false;
var qry = ctx.vw_BuyersByCountryValue.ToList();
var mapped = qry.Select r =>
{
var dict = new Dictionary<string,string>();
dict[r.CODE] = r.TOTALVALUE;
return dict;
});
string strResponse = Newtonsoft.Json.JsonConvert.SerializeObject(mapped);
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.AddHeader("content-length", strResponse.Length.ToString(CultureInfo.InvariantCulture));
Context.Response.Flush();
Context.Response.Write(strResponse);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
You need the NuGet package Newtonsoft.Json
I want to add a new playlist with songs to an existing json file.
I'm using Newtonsoft Json.NET to create a Json file like this:
dynamic GroupObj = new JObject();
GroupObj.Playlist = new JArray() as dynamic;
dynamic PlayListObj = new JObject();
PlayListObj.UniqueId = "";
PlayListObj.Title = "Playlist name";
GroupObj.Playlist.Add(PlayListObj);
PlayListObj.Songs = new JArray() as dynamic;
dynamic SongObj = new JObject();
SongObj.UniqueId = "";
SongObj.Title = "song name";
PlayListObj.Songs.Add(SongObj);
data = GroupObj.ToString();
That outputs this:
{
"Playlist": [
{
"UniqueId": "",
"Title": "Playlist name",
"Songs": [
{
"UniqueId": "",
"Title": "song name",
}
]
}
]
}
How would I modify the Json.NET to add new Objects to the existing Object to get to something like this:
{
"Playlist": [
{
"UniqueId": "",
"Title": "Playlist name",
"Songs": [
{
"UniqueId": "",
"Title": "song name",
}
]
},
{
"UniqueId": "",
"Title": "Playlist name",
"Songs": [
{
"UniqueId": "",
"Title": "song name",
"Lyrics": "song lyrics",
"Location": "location"
}
]
}
]
}
Nevermind, I made a solution by rewriting the whole file. Probably not very resource friendly but for a school project, it works. Thanks
string data;
JsonValue val = JsonValue.Parse("{\"some json data\": some value,}");
JsonArray Pl = val.GetObject().GetNamedArray("Playlist");
for (uint x = 0; x != Pl.Count; x++)//go through each playlist
{
var Pl_title = Pl.GetObjectAt(x).GetNamedString("Title"); //get playlist name
if (Pl_title != txtPlaylistName.Text)//dont do anything if playlist exists
{
var Pl_id = Pl.GetObjectAt(x).GetNamedString("UniqueId");
var Pl_loc = Pl.GetObjectAt(x).GetNamedString("Location");
var Pl_img = Pl.GetObjectAt(x).GetNamedString("ImagePath");
//re-create the playlist
dynamic PlayListObj = new JObject();
PlayListObj.UniqueId = Pl_id;
PlayListObj.Title = Pl_title;
PlayListObj.Location = Pl_loc;
PlayListObj.ImagePath = Pl_img;
GroupObj.Playlist.Add(PlayListObj);
PlayListObj.Songs = new JArray() as dynamic;
JsonArray Sng = Pl.GetObjectAt(x).GetNamedArray("Songs");
for (uint y = 0; y != Sng.Count; y++)
{
var Sng_id = Sng.GetObjectAt(y).GetNamedString("UniqueId");
var Sng_title = Sng.GetObjectAt(y).GetNamedString("Title");
var Sng_lyr = Sng.GetObjectAt(y).GetNamedString("Lyrics");
var Sng_loc = Sng.GetObjectAt(y).GetNamedString("Location");
//re-create the songs in the playlist
dynamic SongObj = new JObject();
SongObj.UniqueId = Sng_id;
SongObj.Title = Sng_title;
SongObj.Lyrics = Sng_lyr;
SongObj.Location = Sng_loc;
PlayListObj.Songs.Add(SongObj);
}
}
else
txtBerror.Text = "The name: " + txtPlaylistName.Text + " already exists.";
}
if (txtPlaylistName.Text != string.Empty)
{
//re-create the playlist
dynamic newPlayListObj = new JObject();
newPlayListObj.UniqueId = "PL " + txtPlaylistName.Text;
newPlayListObj.Title = txtPlaylistName.Text;
newPlayListObj.Location = "";
newPlayListObj.ImagePath = "";
GroupObj.Playlist.Add(newPlayListObj);
newPlayListObj.Songs = new JArray() as dynamic;
for (int a = 0; a != 3; a++)//number of songs
{
dynamic SongObj = new JObject();
SongObj.UniqueId = "Sng " + "file name";
SongObj.Title = "file name";
SongObj.Lyrics = "";
SongObj.Location = "";
newPlayListObj.Songs.Add(SongObj);
}
}
else
txtBerror.Text = "Enter a playlist name";
data = GroupObj.ToString();
await Windows.Storage.FileIO.WriteTextAsync(newFile, data);//write to the file
I am able to create a flat serialized JSON string pretty easily with c#
My issue is I want to create a nested string like this below
[ {
title: "Yes",
id : "1",
menu: [ {
title: "Maybe",
id : "3",
alert : "No",
menu: [ {
title: "Maybe Not",
id : "8",
alert : "No",
menu: []
} ]
} ]
},
{
title: "No",
id : "2",
menu: []
}]
Any help would be great
Are you using MVC 3? - Do something like:
return Json(myObectWithListProperties, JsonRequestBehavior.AllowGet);
I use this to return complex C# objects that match the structure of the JavaScript objects I want.
e.g.:
var bob = new {
name = "test",
orders = new [] {
new { itemNo = 1, description = "desc" },
new { itemNo = 2, description = "desc2" }
}
};
return Json(bob, JsonRequestBehavior.AllowGet);
gives:
{
"name": "test",
"orders": [
{
"itemNo": 1,
"description": "desc"
},
{
"itemNo": 2,
"description": "desc2"
}
]
}
EDIT: A bit more nesting for fun:
var bob = new {
name = "test",
orders = new [] {
new { itemNo = 1, description = "desc" },
new { itemNo = 2, description = "desc2" }
},
test = new {
a = new {
b = new {
something = "testing",
someOtherThing = new {
aProperty = "1",
another = "2",
theThird = new {
bob = "quiteDeepNesting"
}
}
}
}
}
};
return Json(bob, JsonRequestBehavior.AllowGet);
gives:
{
"name": "test",
"orders": [
{
"itemNo": 1,
"description": "desc"
},
{
"itemNo": 2,
"description": "desc2"
}
],
"test": {
"a": {
"b": {
"something": "testing",
"someOtherThing": {
"aProperty": "1",
"another": "2",
"theThird": {
"bob": "quiteDeepNesting"
}
}
}
}
}
}
Try using
using System.Web.Script.Serialization;
//Assumed code to connect to a DB and get data out using a Reader goes here
Object data = new {
a = reader.GetString(field1),
b = reader.GetString(field2),
c = reader.GetString(field3)
};
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(data);
This is built-in and saves you the work of serializing to JSON yourself!
This example assumes you are getting data from a database using some sort of reader, and it then constructs the object you want to serialize using an anonymous class. Your anonymous class can be as simple or complex as you need it to be and the JavaScriptSerializer will handle transforming it to JSON. This approach is also useful because you can easily control the JSON property names it will create in the JSON.
using System.Web.Script.Serialization;
var strNJson = new
{
to = "hello",
notification = new
{
title = "textTitle",
body = "bodyText"
}
};
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(strNJson);
{ "to":"hello",
"notification": {
"title":"titleText",
"body":"bodyText"
}
}
You can make use of the ExpandoObject under the System.Dynamic namespace.
Here is a small snippet for achieving your solution:
dynamic parameters = new dynamic[2];
parameters[0] = new ExpandoObject();
parameters[0].title = "Yes";
parameters[0].id = "1";
parameters[0].menu = new dynamic[1];
parameters[0].menu[0] = new ExpandoObject();
parameters[0].menu[0].title = "Maybe";
parameters[0].menu[0].id = "3";
parameters[0].menu[0].alert = "No";
parameters[0].menu[0].menu = new dynamic[1];
parameters[0].menu[0].menu[0] = new ExpandoObject();
parameters[0].menu[0].menu[0].title = "Maybe Not";
parameters[0].menu[0].menu[0].id = "8";
parameters[0].menu[0].menu[0].alert = "No";
parameters[0].menu[0].menu[0].menu = new dynamic[0];
parameters[1] = new ExpandoObject();
parameters[1].title = "No";
parameters[1].id = "2";
parameters[1].menu = new dynamic[0];
string json = JsonConvert.SerializeObject(parameters, Formatting.Indented);
Console.WriteLine(json);
Here is the work in fiddle
Note: There are other ways to achieve this, but I have been using this approach.