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);
.................
...............
}
Related
I am new to flutter and want to parse the data from a URL that is in json format. The url that I am using is json link .
I want to get the "verse" and "chapter" fields from the json array. I have succeeded in getting the response body in snackbar but not able to get single values. I want to get the "verse" and "chapter" and show then in text box. I am using Dart.
Here is the method that I am using:
_makeGetRequest() async {
// make request
var url = Uri.parse("http://quotes.rest/bible/vod.json");
Response response = await http.get(url);
// sample info available in response
int statusCode = response.statusCode;
Map<String, String> headers = response.headers;
String contentType = headers['content-type'];
String json = response.body;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(json)));
}
#override
void initState() {
super.initState();
streamingController.config(url: "http://stream.zeno.fm/qa8p6uz2tk8uv");
streamingController.play();
_makeGetRequest();
}
Please help me in getting the proper field values and set them in text box as I am trying to solve it from past two days and have tried all solutions from internet but getting exceptions.
use jsonDecode
Map<String,dynamic> data = jsonDecode(response.body);
String verse = data["contents"]["verse"];
dynamic chapter= data["contents"]["chapter"];
however I recommend modeling your data
I’m using Apache HTTP client v 4.3.4. How do I submit JSON data to a URL via the PATCH method? I have tried this
// Create the httpclient
HttpClient httpclient = HttpClientBuilder.create().build();
// Prepare a request object
HttpUriRequest req = null;
if (method.equals(RequestMethod.PATCH))
{
req = new HttpPatch(url);
req.setHeader("Content-type", "application/json");
if (jsonData != null)
{
final StringEntity stringData = new StringEntity(jsonData.toString());
req.setEntity(stringData);
} // if
but on the “req.setEntity” line, I get the compilation error, “The method is undefined”. Note that my request needs to send the JSON data as is, as opposed to putting it into a name-value param pair.
You have cast the HttpPatch object is implicity cast to HttpUriRequest in your code.
The HttpUriRequest interface does not support the setEntity method so you need to cast:
((HttpPatch)req).setEntity(stringData);
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!!!!!
is there any chance to get node-xmpp-server lib to handle messages body in json format (XEP-0295)?
You can serialize json object using stringify, send it, and then unserialize it using parse method
Lets say we have jsonObject variable:
var data = {'some': 'thing', 'bla': 'blah'};
var message = JSON.stringify(data);
and unserialize:
var data = JSON.parse("some serialized message");
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)