How to post JSON - android-json

I want to POST JSON in the following format and GET response.
Mentioned JSON:
{
"success": true,
"data": {
"id": "234576"
"name": "string"
}
}

Create 2 json objects like:
JSONObject parent = new JSONObject();
JSONObject child = new JSONObject();
In the child object, put:
parent.put("success", true);
child.put("id", "234567");
child.put("name", "string");
parent.put("data", child);
and simply call ur service using this parent object.

Related

Fetch data in a POST Request in asp.net core

I am using an external web link to get data and fetch it to json The reason why I need to handle it by the controller is to filter the data of it. Sadly, an api link was programmatically incorrect because instead of requesting it as GET method, it was programmed as POST method. I had this code simple code below but the return was a header data not the actual data of the api.
[HttpPost, Route("get/subproject")]
public ActionResult subproject()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(#"https://thisisjustasample.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage hrm = client.PostAsync("/api/new/get/subproject/details/get_dto", null).Result;
return Ok(hrm);
}
}
The output of the code above is this.
{
"version": "1.1",
"content": {
"headers": [
{
"key": "Content-Length",
"value": [
"29942142"
]
},
{
"key": "Content-Type",
"value": [
"application/json; charset=utf-8"
]
},
{
"key": "Expires",
"value": [
"-1"
]
}
]
}
}
What I need is this data below.
{
"sub_project_id": 267892,
"engineeringMigrationId": 0,
"modality_id": 21,
"id": null,
"reportID": null,
"month": null,
"year": null,
"cycle_id": 204
}
Any help would be appreciated. Thanks in advance.
Don't return hrm directly, If you want to get the response data, you need return.
hrm.Content.ReadAsStringAsync().Result
Demo
1.return Ok(hrm);
2.return Ok(hrm.Content.ReadAsStringAsync().Result);

Return string from Web API .NET Core get operation

I have a get operation that I want to return a string from. An example would be
"000875"
When I return this string from a controller in my Web API Controller in full .NET, it formats it like this:
{
"Property": "000875"
}
When I return the string in my converted .NET Core Controller it returns this:
{
"$id": "1",
"$type": "System.Net.Http.HttpResponseMessage, System.Net.Http",
"Version": "1.1",
"Content": {
"$id": "2",
"$type": "System.Net.Http.StringContent, System.Net.Http",
"Headers": [
{
"Key": "Content-Type",
"Value": [
"application/json; charset=utf-8"
]
}
]
},
"StatusCode": "OK",
"ReasonPhrase": "OK",
"Headers": [],
"TrailingHeaders": [],
"RequestMessage": null,
"IsSuccessStatusCode": true
}
It is interesting to note that the value is not even in there!
I am running some interesting JSON Serialization to make BreezeJs work with .NET Core. It is possible that it is the cause of this weirdness:
.AddNewtonsoftJson(opt =>
{
// Let Breeze say how we serialize. This adds in the Type and Id options the way breeze expects
var jsonSerializerSettings = JsonSerializationFns.UpdateWithDefaults(opt.SerializerSettings);
......
I am hoping for a way to get strings through without all this mess. Can that be done?
I get the impression that the subject action definition returns HttpResponseMessage.
public HttpResponseMessage MyAction(....
HttpRequestMessage is no longer a first class citizen in asp.net-core framework and will be treated as a normal model and serialized.
That explains the JSON you are seeing with your controller
The syntax needs to be updated to return IActionResult derived responses
public IActionResult MyAction() {
//...
return Ok("000875");
}
ActionResult<T>
public ActionResult<string> MyAction() {
//...
if(somecondition)
return NotFound();
return "000875";
}
or the model itself.
public string MyAction() {
//...
return "000875";
}
Reference Controller action return types in ASP.NET Core Web API

Modify data using AJV for Json Schema

I'm using AJV (Another Json schema validator) on NodeJs.
I've the following schema
var schema = {
"$id": "testSchema.json",
"type": "object",
"$schema": "http://json-schema.org/draft-06/schema#",
"additionalProperties": false,
"properties": {
"userId": {
"type": "integer"
},
"userName": {
"type": "string"
},
"uniqueID": {
"type": "integer"
}
}
}
I need to overwrite unqiueID property by a value that I could somehow pass to Json schema or AJV.
I think the above can be done using AJV addKeyword method, tried using it but failed because I don't know how to manipulate (and return) data value from AJV custom keywords.
Is possible to modify data with AJV ? or are there any other possible ways to do it??
Thank you!
You can create a custom keyword with function that will do whatever your want to data.
var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});
ajv.addKeyword('my_id_rewrite', {
type: 'object',
compile: function (sch, parentSchema) {
return function (data) {
console.log(data)
data['my_id']=parentSchema.my_id_rewrite;
return true;
}
}
});
var schema = { "my_id_rewrite": 2 };
var validate = ajv.compile(schema);
o = {"my_id":1}
console.log(validate(o)); // true
console.log(o); // Object {my_id: 2}
https://runkit.com/embed/cxg0vwqazre3

Custom ASP.Net Core JSON model binder

My posted JSON object is this:
{{
"emails": [
{
"To": "info#gmail.com",
"Subject": "Subject",
"Body": "Body",
"ID": "d3d13242-6eff-4c57-b718-ef5ad49fe301"
},
{
"To": "hr#gmail.com",
"Subject": "Subject",
"Body": "Body",
"ID": "101edaf0-fcb4-48fc-9e9e-0d7492b591b0"
}
]
}}
By default ASP.NET model binder will not bind this JSON object and as you can see here I get always null when I send post request to the API:
[HttpPost, Route("Send")]
public async Task<IActionResult> Send(Email[] emails)
{
var toSave = from email in emails
select new EmailQueueItem
{
Html = true,
To = email.To,
Subject = email.Subject,
Body = email.Body
};
await Database.BulkInsert(toSave.ToArray());
return Ok();
}
emails property is always null. I would appreciate any help for creating custom model binder that handel this kind of JSON objects.
The issue is that you are actually sending an object containing one property named emails, not an array, to the controller
Option one:
The client object needs to contain just the array
[
{
"To": "info#gmail.com",
"Subject": "Subject",
"Body": "Body",
"ID": "d3d13242-6eff-4c57-b718-ef5ad49fe301"
},
{
"To": "hr#gmail.com",
"Subject": "Subject",
"Body": "Body",
"ID": "101edaf0-fcb4-48fc-9e9e-0d7492b591b0"
}
]
Then read the array from the request body
public async Task<IActionResult> Send([FromBody]Email[] emails)
Option 2:
When you define the array like this in the client
{
"emails":...
}
You need to match that object setup on the controller by defining a model which contains a property called emails
public class RequestModel
{
public Email[] emails { get; set; }
}
Then in the controller method, use the model and read it from the body
public async Task<IActionResult> Send([FromBody]RequestModel emails)

extjs nested json store rails

i am trying to post ext js json store that has some hard coded records..
there is one-to-many relationship between Customer & Product..
{
"customers": [
{
"id": 123,
"name": "Ed",
"products": [
{
"id": 50,
"prodnm": "xyz",
rate:20,
},
{
"id": 60,
"prodnm": "abc",
rate:30,
}
]
}
]
}
iam using rails & want to check whether i m getting proper json response..plz help..
For that you can use this code to get the json from store.
function getJsonOfStore(store){
var datar = new Array();
var jsonDataEncode = "";
var records = store.getRange();
for (var i = 0; i < records.length; i++) {
datar.push(records[i].data);
}
jsonDataEncode = Ext.util.JSON.encode(datar);
return jsonDataEncode;
}
print that json in console then copy that json and past it here, click on format it will show you a formated json.
The best way to check the response is by using Fiddler