Hoping you'd be able to assist me with this error - I am getting
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
at the time when Client.Execute is called, I've shared my code below:
Thanks in Advance!
var Client = new RestClient();
Client.BaseUrl = new Uri("http://dummyurl.com/");
Client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("username", "password");
var eventlist = new List<string>();
var request = new RestRequest(Method.POST);
request.AddHeader("event", "application/json");
string jsonBody = #"{'xxxxx':'xxxx',
'xxxx':'Xxxxx'}";
JObject jsonObject = JObject.Parse(jsonBody);
request.AddBody(jsonObject);
IRestResponse response = Client.Execute(request); //<<<--Throws Stackoverflow exception
var content = JsonConvert.DeserializeObject(response.Content);
It blows up on serialising the JObject instance. You don't need to overload your code with repeated serialization and JSON parsing.
To pass a ready-made JSON as the request body, just use AddParamerter(contentType, jsonString, ParameterType.RequestBody);
Set the content type accordingly to application/json or whatever your server wants.
Related
i am sending the data through postman to asp.net webapi. But i am getting the exception.Need to send both file and json data.
Get the json format also in C# coding as string.
public JsonResult FileUploadDetails(HttpPostedFileBase[] Files,string request)
{
//Stream req = Request.InputStream;
//string reqparm = Request.QueryString["request"];
//req.Seek(0, System.IO.SeekOrigin.Begin);
//var jsonStr = new StreamReader(reqparm).ReadToEnd();
JObject obj = JObject.Parse(request);
.................
...............
}
I know we can send a json object via Postman as a POST request. However, I wish to send multiple such json Objects(hundreds) consecutively via. Postman.
Is there some way I can achieve that? I am stuck and will highly appreciate some solutions.
TIA:)
So I ended up sending the json data via. a java code through POST requests.
Since I needed this only for load testing, I didn't care much about the code efficiency here. Might be useful for someone
String line;
JSONParser jsonParser = new JSONParser();
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
while((line = br.readLine()) != null) {
JSONObject jsonObject = (JSONObject) jsonParser.parse(line);
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://url");
StringEntity params = new StringEntity(jsonObject.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);.
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
}
I have a JsonObject created using Google Gson.
JsonObject jsonObj = gson.fromJson(response1_json, JsonElement.class).getAsJsonObject();
Also i made some modification to existing jsonobj as below :
JsonObject newObject = new JsonObject();
newObject.addProperty("age", "50");
newObject.addProperty("name", "X");
jsonObj.get("data").getAsJsonArray().add(newObject);
Now, using rest assured, i need to send the post request with this jsonobject. I tried the following but it doesn't work and throws exception:
Response postResponse =
given()
.cookie(apiTestSessionID)
.header("Content-Type", "application/json")
.body(jsonObj.getAsString())
.when()
.post("/post/Config");
Please guide me on this.
Try below code to send Json to a Post request using Rest-assured
//Get jsonObject from response
JsonObject jsonObj = gson.fromJson(response1_json, JsonElement.class).getAsJsonObject();
//Create new jsonObject and add some properties
JsonObject newObject = new JsonObject();
newObject.addProperty("age", "50");
newObject.addProperty("name", "X");
//Get jsonarray from jsonObject
JsonArray jArr = jsonObj.get("data").getAsJsonArray();
//Add new Object to array
jArr.add(newObject);
//Update new array back to jsonObject
jsonObj.add("data", jArr);
Response postResponse =
given()
.cookie(apiTestSessionID)
.contentType("application/json")
.body(jsonObj.toString())
.when()
.post("/post/Config");
I am looking for some help with a datatable conversion into a JObject. I am using C# in visual studio along with the Newtonsoft JSON .net library. I have retrieved my datatable from my database.
From here I took the data table and processed it through this class:
public string DataTableToJSONString(DataTable table)
{
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(table,Formatting.Indented);
return JSONString;
}
Now that the object has been converted to a JSONString successfully (It throws no errors at this point) via the Newtonsoft JSON.net Library, I am unable to parse it into a JObject with this code:
Note: "json" is the string variable I placed the returned value from the DatatabletoDataTableToJSONString() method into..
JObject job = JObject.Parse(json);
I continuously get the following error...
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
The reason I need it in the form of a JObject it to pass it into the following post method for an API:
public static async Task<JObject> Post(string url, JObject data)
{
// Create an HttpClient instance
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = CreateBasicHeader(ClientContext.Username, ClientContext.Password);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Send a request asynchronously and continue when complete
var requestbody = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, requestbody);
dynamic content = await response.Content.ReadAsAsync<JObject>();
// Check that response was successful or throw exception
try
{
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
throw new Exception("Status Code: " + response.StatusCode + "\r\nMessage: " + content[0].ToString(), ex);
}
// Read response asynchronously as a JObject
return content;
}
I would appreciate any help on this as I have been researching for 2 weeks with no luck. This one is really killing me. Thanks in advance to all who take the time to examine this.
UPDATE: I ended up adding in the following bit of code as I realized I was returning an array when I pulled the data table.
string jsonresult = JsonConvert.SerializeObject(dt);
JArray aray = JArray.Parse(jsonresult);
//I then have code for the API login credentials here....
foreach (JObject item in aray)
{
ApiClient.Post(Url, item).Wait();
}
This appears to pass in the JObjects just fine into the post method although I get the following error:"AggregateException was unhandled..." I set a break point and the flaw appears to happen at the:
try
{
response.EnsureSuccessStatusCode();
}
After attempting the response.ensuresuccessstatusCode(); The program of course jumps to the catch....
catch (Exception ex)
{
throw new Exception("Status Code: " + response.StatusCode + "\r\nMessage: " + content.message.ToString(), ex);
}
Again, any help would be appreciated. I am almost there with this. After it posts, I will be done.... Thanks again in advance to everyone. I apologize for being long winded.
Your problem is that JSON has two types of containers: arrays and objects:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace).
The corresponding LINQ to JSON class is JObject.
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
The corresponding LINQ to JSON class is JArray.
So, how does Json.NET serialize a data table? From the documentation Serialize a DataSet, we can see that each table is serialized as an array.
If you attempt to parse a JSON string whose root object is an array into a JObject, you will get this exception.
Instead, you must return a JArray, or better yet a JToken which is the root class for all JSON entities:
public static async Task<JToken> Post(string url, JObject data)
{
// Create an HttpClient instance
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = CreateBasicHeader(ClientContext.Username, ClientContext.Password);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Send a request asynchronously and continue when complete
var requestbody = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, requestbody);
dynamic content = await response.Content.ReadAsAsync<JToken>();
// Check that response was successful or throw exception
try
{
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
throw new Exception("Status Code: " + response.StatusCode + "\r\nMessage: " + content[0].ToString(), ex);
}
// Read response asynchronously as a JToken
return content;
}
I am answering this thread and closing it as the original question has technically been answered. I simply converted the JArray into its respective JObjects with the following bit of code.
foreach (JObject item in aray)
{
ApiClient.Post(Url, item).Wait();
}
Although I am still working on debugging, I was technically able to pull the Object out of the array that I got from the data table.
Thanks all!!!!!
I am trying to POST some JSON data to my Server. I am using simple code which I have attained from: Http Post for Windows Phone 8
Code:
string url = "myserver.com/path/to/my/post";
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
//create some json string
string json = "{ \"my\" : \"json\" }";
// convert json to byte array
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);
// Write the bytes to the stream
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
I am getting an error though on await and Task:
Anyone see the obvious error?
Fixed it by changing method signature to:
public async Task ReportSighting(Sighting sighting)