I have written a azure function which will return data into json string format but i want data into json object so that i can directly use that array output for next step into logic app.
azure function code -
composeMessage = "{\"__metadata\": {\"id\": "+obj.id+",\"uri\": "+obj.uri+",\"dateForSystem\": "+obj.dateForSystem + ",\"timeForSystem\": "+obj.timeForSystem + "}";
composeMessageList.Add(composeMessage);
outputDerivedTableKey = string.Empty;
startIndex = 0;
}
var jsonToReturn = JsonConvert.SerializeObject(composeMessageList);
return new HttpResponseMessage(HttpStatusCode.OK) {
Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
getting output like -
[
"{\"__metadata\": {\"id\": ,\"uri\": ,\"type\": },\"dateForSystem\": 2019-05-17,\"timeForSystem\": 13:15:51}",
"{\"__metadata\": {\"id\": ,\"uri\": ,\"type\": },\"dateForSystem\": 2019-05-17,\"timeForSystem\": 13:15:51}",
"{\"__metadata\": {\"id\": ,\"uri\": ,\"type\": },\"dateForSystem\": 2019-05-17,\"timeForSystem\": 13:15:51}",
]
But I can't pass this array to foreach in logic app i'm excepting output format like below from azure function -
[
{
"__metadata": {
"id": "",
"uri": "",
"type": ""
},
"dateForSystem": "2019-05-17",
"timeForSystem": "13:15:51"
},
{
"__metadata": {
"id": "",
"uri": "",
"type": ""
},
"dateForSystem": "2019-05-17",
"timeForSystem": "13:15:51"
},
{
"__metadata": {
"id": "",
"uri": "",
"type": ""
},
"dateForSystem": "2019-05-17",
"timeForSystem": "13:15:51"
},
]
How can i achieve this format output from azure function ?
Or how to format this into logic app?
The problem is that the serialized object is a list of string so Json.Net serializes it as an array of string.
Here is a simple function that use dynamic objects but you can also create a class for your composeMessage object:
[FunctionName("Function1")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
ILogger log)
{
var composeMessageList = new List<object>();
for(var i = 0; i < 5; i++)
{
var composeMessage = new
{
__metadata = new
{
id = "",
uri = "",
type = ""
},
dateForSystem = "2019-05-17",
timeForSystem = "13:15:51"
};
composeMessageList.Add(composeMessage);
}
var jsonToReturn = JsonConvert.SerializeObject(composeMessageList);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
};
}
Related
I'm trying to create a POST call using HttpClient that I have fully working in Postman. Here is the body I'm sending in Postman:
{
"searchType": "games",
"searchTerms": [
"mario"
],
"searchPage": 1,
"size": 20,
"searchOptions": {
"games": {
"userId": 0,
"platform": "",
"sortCategory": "popular",
"rangeCategory": "main",
"rangeTime": {
"min": 0,
"max": 0
},
"gameplay": {
"perspective": "",
"flow": "",
"genre": ""
},
"modifier": ""
},
"users": {
"sortCategory": "postcount"
},
"filter": "",
"sort": 0,
"randomizer": 0
}
}
I have this written as the following in C#:
var client = _httpClientFactory.CreateClient(HttpClients.HowLongToBeat.ToString());
var request = new HowLongToBeatRequest
{
SearchType = "games",
SearchTerms = searchTerm.Trim().Split(" "),
SearchPage = 1,
Size = 20,
SearchOptions = new SearchOptions
{
Games = new SearchOptionsGames
{
UserId = 0,
Platform = "",
SortCategory = "popular",
RangeCategory = "main",
RangeTime = new SearchOptionsGamesRangeTime
{
Min = 0,
Max = 0
},
Gameplay = new SearchOptionsGamesGameplay
{
Perspective = "",
Flow = "",
Genre = ""
},
Modifier = ""
},
Users = new SearchOptionsUsers
{
SortCategory = "postcount"
},
Filter = "",
Sort = 0,
Randomizer = 0
}
};
//var json = JsonSerializer.Serialize(request);
//var content = new StringContent(json, Encoding.UTF8, "application/json");
//var response = await client.PostAsync("api/search", content);
var response = await client.PostAsJsonAsync("api/search", request, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
return new HowLongToBeatResponse();
I have this set up as
The url I'm hitting is: https://www.howlongtobeat.com/api/search and I'm setting it up like so in my Startup.cs
services.AddHttpClient(HttpClients.HowLongToBeat.ToString(), config =>
{
config.BaseAddress = new Uri("https://www.howlongtobeat.com/");
config.DefaultRequestHeaders.Add("Referer", "https://www.howlongtobeat.com/");
});
I am passing this Referer header in my Postman collection as well.
Basically, I can't figure out why this code gets a 403 in C# but the Postman that I think is exactly the same is getting a successful response. Am I missing something?
Let me know if there's any missing info I can provide.
I solved my problem. The issue was that this specific API required a User Agent header specified.
I think the problem is here, The BaseAddress property needs to be suffixed (https://www.howlongtobeat.com/) with a forward slash and here you already set route as well, change it to
services.AddHttpClient(HttpClients.HowLongToBeat.ToString(), config =>
{
config.BaseAddress = new Uri("https://www.howlongtobeat.com/");
config.DefaultRequestHeaders.Add("Referer", "https://www.howlongtobeat.com/api/search");
});
And then
var response = await client.PostAsJsonAsync("api/search", request, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
Updated:
try this, here I have hard-coded the Base URL for testing purposes.
try
{
var data_ = JsonConvert.SerializeObject(root);
var buffer_ = System.Text.Encoding.UTF8.GetBytes(data_);
var byteContent_ = new ByteArrayContent(buffer_);
byteContent_.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string _urls = "https://www.howlongtobeat.com/api/search";
var responses_ = await _httpClient.PostAsJsonAsync(_urls, byteContent_);
if (responses_.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("[GetPrimeryAccount] Response: Success");
string body = await responses_.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); ;
}
I have used jquery datatable Server-side processing in my application (asp web form ), after the data returned, paging, searching and sorting do not work. I've read several cases here on the forum of similar or equal problems, but I still haven't been able to solve mine. Could you look at my code, please?
datatable
<script type="text/javascript">
$(document).ready(function () {
$("#stockDatatable").DataTable({
"processing": true, //show processing message
"serverSide": true, //is server side
"filter": true, //allow filter
"ajax": {
"url": "WebForm2.aspx/GetData", //endpoint to get data
"contentType": "application/json",
"type": "GET",
"dataType": "JSON",
"data": function (d) {
return d;
},
"dataSrc": function (json) {
json.draw = json.d.draw;
json.recordsTotal = json.d.recordsTotal;
json.recordsFiltered = json.d.recordsFiltered;
json.data = json.d.data;
var return_data = json.d.data;
return return_data;
}
},
"columns": [ // columns to populate
{ "data": "Id" },
{ "data": "Code"},
{ "data": "Type" },
{ "data": "Text_Description" },
{ "data": "Date_Time" },
{ "data": "Date_Created"},
{ "data": "Added_by" },
],
});
});
</script>
Code Behind (Webform2.cs)
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static object GetData()
{
DataTables result = new DataTables();
using (var db = new MunchData())
{
string search = HttpContext.Current.Request.Params["search[value]"];
string draw = HttpContext.Current.Request.Params["draw"];
string order = HttpContext.Current.Request.Params["order[0][column]"];
string sortColumnDirection = HttpContext.Current.Request.Params["order[0][dir]"];
int startRec = Convert.ToInt32(HttpContext.Current.Request.Params["start"]);
int pageSize = Convert.ToInt32(HttpContext.Current.Request.Params["length"]);
string start = HttpContext.Current.Request.Params["start"];
int skip = start != null ? Convert.ToInt32(start) : 0;
var data = db.Machineinfoes.OrderByDescending(p => p.Id).ToList();
int totalRecords = data.Count;
int recFilter = data.Count;
result.draw = Convert.ToInt32(draw);
result.recordsTotal = totalRecords;
result.recordsFiltered = recFilter;
result.data = data.Skip(skip).Take(pageSize).ToList();
}
return result;
}
I'm reading my json file from and trying to replace the property values. JSON file is below.
{
"fields": {
"summary": "summaryValue",
"project": {
"key": "projectValue"
},
"priority": {
"name": "priorityValue"
},
"Requestor": {
"name": "RequestorValue"
},
"issue": {
"name": "issueValue"
},
"labels": "LabelValue",
"customfield_xyz": "customfield_xyzValue"
}
}
How can I replace the value for each item inside the fields property ?
for ex:
{"fields": {
"summary": "NewsummaryValue",
"project": {
"key": "NewprojectValue"
},
"priority": {
"name": "NewpriorityValue"
}
}
}
Below is the code to parse my json file,
StreamReader r = new StreamReader(filepath);
var jsondata = r.ReadToEnd();
var jobj = JObject.Parse(jsondata);
foreach (var item in jobj.Properties())
{
\\replace code
}
I do not know exactly what you want. But I changed the json information in the code snippet as you wanted.
dynamic dataCollection = JsonConvert.DeserializeObject<dynamic>(jsonData);
string summary = dataCollection["fields"]["summary"];
string project = dataCollection["fields"]["project"]["key"];
string priority = dataCollection["fields"]["priority"]["name"];
dynamic json = new JObject();
json.summary = summary;
json.project = project;
json.priority = priority;
dynamic jsonRoot = new JObject();
jsonRoot.fields = json;
Console.WriteLine(jsonRoot.ToString());
output:
In my API testing I am using Jcontainer to Convert response to Json.
Ex:
[Test]
public void GetUsersList()
{
var response = us.UserList();
JContainer jsonresponse = rh.ConvertResponseToJson(response);
}
I am trying to the following validation against the Json
Verify if all Keys are present (If all keys in json are present, like id, timestamp, type etc..)
Here is my json
[
{
"id": "aa0db615-d4cb-4466-bc23-0e0083002330",
"timestamp": "2020-02-11T19:00:00-05:00",
"type": 33554432,
"info": "Full Synchronization request for all endpoints",
"schedule": "once",
"lastRun": null,
"flags": 6,
"creator": null,
"isEditable": true,
"location": 0,
"duration": null
},
{
"id": "70baa28c-e270-447b-b88a-20d30a9542db",
"timestamp": "2020-02-11T19:00:00-05:00",
"type": 33554432,
"info": "Full Synchronization request for all endpoints",
"schedule": "once",
"lastRun": null,
"flags": 6,
"creator": null,
"isEditable": true,
"location": 0,
"duration": null
}
]
Here is my Convert respone to Json for reference
public JContainer ConvertResponseToJson(HttpWebResponse response)
{
string localString;
if (response.ContentEncoding.Contains("application/xml"))
{
// Convert the escaped Stream into an XML document.
ConfigXmlDocument xmlDocument = new ConfigXmlDocument();
xmlDocument.LoadXml(ConvertResponseStreamToString(response));
// Now convert the properly-escaped JSON for the response into a JContainer
localString = JsonConvert.SerializeXmlNode(xmlDocument);
}
else
localString = ConvertResponseStreamToString(response);
return JToken.Parse(localString) as JContainer;
}
For now I created a model of the Json to read it by array index. But I am doing mutiple assetions to vaidate all keys. I want to just loop through them. Here is what i have so far
var response = us.UserList();
JContainer jsonresponse = rh.ConvertResponseToJson(response);
var castedModel = Jsonresponse.ToObject<IList<Model>>();
Assert.IsNotNull(castedModel[0].info); //This is repeated I am trying to avoid this
Assert.IsNotNull(castedModel[0].task);
Assert.IsNotNull(castedModel[0].timestamp)
You could just use a for loop.
var castedModel = Jsonresponse.ToObject<IList<Model>>();
for(int i = 0; i < castedModel.Count; i++)
{
Assert.IsNotNull(castedModel[i].info);
Assert.IsNotNull(castedModel[i].task);
Assert.IsNotNull(castedModel[i].timestamp)
{
I am trying to get json data from my jquery ajax in ashx file, but result is somehow unusable. how can I get and bind it to dynamic or alternative?
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
var result = new StreamReader(context.Request.InputStream).ReadToEnd();
}
result
maintype=Entity.JobApplication&feeds=&fields%5B0%5D%5Bkey%5D=EmployeeRequest&fields%5B0%5D%5Bvalue%5D=1&fields%5B1%5D%5Bkey%5D=State&fields%5B1%5D%5Bvalue%5D=1&fields%5B2%5D%5Bkey%5D=FirstName&fields%5B2%5D%5Bvalue%5D=11&fields%5B3%5D%5Bkey%5D=LastName&fields%5B3%5D%5Bvalue%5D=22
**json data**
var data = {
"maintype": "Entity.JobApplication",
"feeds": "",
"fields": [
{
"key": "EmployeeRequest",
"value": ""
},
{
"key": "State",
"value": ""
},
{
"key": "FirstName",
"value": ""
},
{
"key": "LastName",
"value": ""
}
]
};
var data = <%=AjaxJSON%>;
for (var i in data.fields)
{
var o = $("[prop=" + data.fields[i].key + "]");
data.fields[i].value = o.val();
}
genericAjax("/_Handler/CreateEntity.ashx", data);
You need to use WebUtility.UrlDecode to decode your string.
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
var result =WebUtility.UrlDecode(new StreamReader(context.Request.InputStream).ReadToEnd());
}
Result:
maintype=Entity.JobApplication&feeds=&fields[0][key]=EmployeeRequest&fields[0][value]=1&fields[1][key]=State&fields[1][value]=1&fields[2][key]=FirstName&fields[2][value]=11&fields[3][key]=LastName&fields[3][value]=22
By the way, the data you get is not Json-ready format.
Here you can parse it to more close to json (Add reference: System.Web, System.Web.Extension):
string s = "maintype=Entity.JobApplication&feeds=&fields%5B0%5D%5Bkey%5D=EmployeeRequest&fields%5B0%5D%5Bvalue%5D=1&fields%5B1%5D%5Bkey%5D=State&fields%5B1%5D%5Bvalue%5D=1&fields%5B2%5D%5Bkey%5D=FirstName&fields%5B2%5D%5Bvalue%5D=11&fields%5B3%5D%5Bkey%5D=LastName&fields%5B3%5D%5Bvalue%5D=22";
var dict = System.Web.HttpUtility.ParseQueryString(s);
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(
dict.AllKeys.ToDictionary(k => k, k => dict[k]));
You will get:
{"maintype":"Entity.JobApplication","feeds":"","fields[0][key]":"EmployeeRequest","fields[0][value]":"1","fields[1][key]":"State","fields[1][value]":"1","fields[2][key]":"FirstName","fields[2][value]":"11","fields[3][key]":"LastName","fields[3][value]":"22"}
Do a few more step you can convert it to json.
I solved it by using JSON.stringify(data)
genericAjax("/_Handler/CreateEntity.ashx", JSON.stringify(data));