How to access JSON? - json

I am wrote API method, after calling that method , I got my response like
[
{
"spark_version": "7.6.x-scala2.12"
}
]
Now I want to have variable in my API method which store value 7.6.x-scala2.12.
API Controller method
[HttpGet]
public IActionResult GetTest(int ActivityId)
{
string StoredJson = "exec sp_GetJobJSONTest " +
"#ActivityId = " + ActivityId ;
var result = _context.Test.FromSqlRaw(StoredJson);
return Ok(result);
}
So how this variable should call on this response to get string stored in spark_version?
Thank you

As you have the JavaScript tag, here's how you'd do it in JS:
If you are able to call your API method, then you can just assign the response to a variable. For example, if you are calling it using the fetch API, it would look something like:
let apiResponse;
fetch('myApiUrl.com').then((response) => {
if (response.status === 200) {
apiResponse = response.body;
console.log('Response:', apiResponse[0]['spark_version']);
}
});
(I defined the variable outside the then to make it globally accessible)

Related

How can I send custom object from my callable Firebase Cloud Function in TypeScript to my Unity app?

I'm trying to use Firebase and its callable Cloud Functions for my Unity project.
With the docs and different posts I found on the web I struggle to understand how returning data works. (I come from Azure Functions in C#)
I use TypeScript, and try to return a custom object CharactersResponse:
export class CharactersResponse //extends CustomResponse
{
Code!: CharactersCode;
CharacterID?: string;
}
export enum CharactersCode
{
Success = 0,
InvalidName = 2000,
CharacterNameAlreadyExists = 2009,
NoCharacterSlotAvailable = 3000,
InvalidCharacterClass = 4000,
EmptyResponse = 9000,
UnknownError = 9999,
}
(Custom Response is a parent class with only an UnknownErrorMessage string property, that I use for adding extra message when needed, but only in Unity. I don't need it in my functions.)
I have the same in my C# Unity Project:
public class CharactersResponse : CustomResponse
{
public CharactersCode Code;
public string CharacterID;
}
public enum CharactersCode
{
Success = 0,
InvalidName = 2000,
CharacterNameAlreadyExists = 2009,
NoCharacterSlotAvailable = 3000,
InvalidCharacterClass = 4000,
EmptyResponse = 9000,
UnknownError = 9999,
}
I'm still learning but I found it useful to do this way for displaying correct messages in Unity (and also regarding localization).
When the Code is 0 (Success), I will usually need to get some data at the same time like in this example CharacterID, or CharacterLevel, CharacterName etc.. CharacterResponse will be used for all functions regarding Characters like "GetAllCharacters", "CreateNewCharacter" etc..
My Function (CreateNewCharacter) looks like this:
import * as functions from "firebase-functions";
import { initializeApp } from "firebase-admin/app";
import { getFirestore } from "firebase-admin/firestore";
import { CharactersResponse } from "./CharactersResponse";
import { CharactersCode } from "./CharactersResponse";
import { StringUtils } from "../Utils/StringUtils";
// DATABASE INITIALIZATION
initializeApp();
const db = getFirestore();
// CREATE NEW CHARACTER
export const CreateNewCharacter =
functions.https.onCall((data, context) =>
{
// Checking that the user is authenticated.
if (!context.auth)
{
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
'while authenticated.');
}
// TEST
data.text = '';
// Authentication / user information is automatically added to the request.
const uid: string = context?.auth?.uid;
const characterName: string = data.text;
// Check if UserID is present
if (StringUtils.isNullOrEmpty(uid))
{
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError('failed-precondition', 'Missing UserID in Auth Context.');
}
const response = new CharactersResponse();
if (StringUtils.isNullOrEmpty(characterName))
{
response.Code = CharactersCode.InvalidName;
console.log("character name null or empty return");
return response; // PROBLEM IS HERE *****************
}
console.log("end return");
return "Character created is named : " + characterName + ". UID = " + uid;
});
In Unity, the function call looks like this:
private static FirebaseFunctions functions = FirebaseManager.Instance.Func;
public static void CreateNewCharacter(string text, Action<CharactersResponse> successCallback, Action<CharactersResponse> failureCallback)
{
Debug.Log("Preparing Function");
// Create the arguments to the callable function.
var data = new Dictionary<string, object>();
data["text"] = text;
// Call the function and extract the operation from the result.
HttpsCallableReference function = functions.GetHttpsCallable("CreateNewCharacter");
function.CallAsync(data).ContinueWithOnMainThread((task) =>
{
if (task.IsFaulted)
{
foreach(var inner in task.Exception.InnerExceptions)
{
if (inner is FunctionsException)
{
var e = (FunctionsException)inner;
// Function error code, will be INTERNAL if the failure
// was not handled properly in the function call.
var code = e.ErrorCode;
var message = e.Message;
Debug.LogError($"Code: {code} // Message: {message}");
if (failureCallback != null)
{
failureCallback.Invoke(new CharactersResponse()
{
Code = CharacterCode.UnknownError,
UnknownErrorMessage = $"ERROR: {code} : {message?.ToString()}"
});
}
}
}
}
else
{
Debug.Log("About to Deserialize response");
// PROBLEM IS HERE *********************
CharactersResponse response = JsonConvert.DeserializeObject<CharactersResponse>(task.Result.Data.ToString());
Debug.Log("Deserialized response");
if (response == null)
{
Debug.LogError("Response is NULL");
}
else
{
Debug.Log("ELSE");
Debug.Log($"Response: {response}");
Debug.Log(response.Code.ToString());
}
}
});
}
The problem :
In my Unity C# code, task.Result.Data contains the CharactersCode I've set in my function, but I can't find a way to convert it to CharactersResponse. (It worked in Azure Functions). Moreover, the line just after Deserialization Debug.Log("Deserialized response"); is not executed. The code seems stuck in the deserialization process.
I tried with and without extending my TypeScript class with CustomResponse(because I don't need it in my Function so I didn't extended it at first).
I also tried setting a CharacterID because I thought maybe it didn't like the fact that this property was missing but the result is the same.
I don't understand what is the problem here? If any of you can help.
Thanks.
HttpsCallableResult.Data is of type object!
=> Your ToString will simply return the type name something like
System.Object
or in your case the result is a dictionary so it prints out that type.
=> This is of course no valid JSON content and not what you expected.
Simply construct the result yourself from the data:
var result = (Dictionary<string, object>)task.Result.Data;
CharactersResponse response = new CharactersResponse
{
Code = (CharactersCode)(int)result["Code"],
CharacterID = (string)result["CharacterID"];
};
I wanted to implement derHugo's solution but couldn't find a way to convert task.Result.Data to Dictionary<string, object>.
The code was stuck at var result = (Dictionary<string, object>)task.Result.Data; even in step by step debugging and no error popped up.
OLD SOLUTION:
So I did a little research and stumbled upon this post and ended up using this instead :
var json = JsonConvert.SerializeObject(task.Result.Data);
CharactersResponse response = JsonConvert.DeserializeObject<CharactersResponse>(json);
I basically convert the task.Result.Data to JSON and convert it back to CharactersResponse and it works. I have what I wanted.
However, I seem to understand that it is not the best solution performance-wise, but for now it is okay and I can now move forward in the project, I'll try to find a better solution later.
NEW SOLUTION:
I wanted to try one last thing, out of curiosity. I wondered what if I convert to JSON at the beginning (in my function) instead of at the end (in my Unity app). So I did this in my function's TypeScript code:
response.Code = CharactersCode.InvalidName;
var r = JSON.stringify(response); // Added this line
return r; // return 'r' instead of 'response'
In my C# code, I retried this line of code:
CharactersResponse response = JsonConvert.DeserializeObject<CharactersResponse>(task.Result.Data.ToString());
And it works ! I just needed to convert my object to JSON in my function before returning it. It allows me to "save" one line of code to process on the client side compared to the old solution.
Thanks derHugo for your answer as it helped me finding what I want.

i cant send json to asp mvc using angularjs

im trying to send json parameter to asp request handler like this:
$scope.SaveCarUpgrades = function () {
var parameter = JSON.stringify(resultCarUpgrades);
$http.get("/ProfileEditor/saveUserCarUpgrades/" + $scope.useridCarUpgrades,
{ params: { name: parameter }}
).then(onsuccess, onfail);
function onsuccess(response) {
if (response.status == 200) {
$scope.saveUpgradesResult = "save upgrades success";
} else {
$scope.saveUpgradesResult = "save upgrades failed" + response.status;
}
}
function onfail(response) {
$scope.saveUpgradesResult = "save upgrades failed" + response.status;
// $scope.saveUpgradesResult = parameter;
}
}
c# request handler is something very simpe. its just for testing right now:
public string SaveUserCarUpgrades(string id)
{
string result = id;
var data = Request.QueryString["name"];
return id;
}
the problem is i always get 404 if if use json as parameter. (its a complex long json) but as simple json or simple string the response is fine. i dont think the problem is mime type as i set it in iis express in devcmd.
thank you for helping

JSON returning with "\" (Lambda)

I am using AWS Lambda to get JSON from the open weather api and return it.
Here is my code:
var http = require('http');
exports.handler = function(event, context) {
var url = "http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=b1b15e88fa797225412429c1c50c122a";
http.get(url, function(res) {
// Continuously update stream with data
var body = '';
res.on('data', function(d) {
body += d;
});
res.on('end', function() {
context.succeed(body);
});
res.on('error', function(e) {
context.fail("Got error: " + e.message);
});
});
}
It works and returns the JSON, but it is adding backslashes before every " like so:
"{\"coord\":{\"lon\":145.77,\"lat\":-16.92},\"weather\":[{\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04d\"}],\"base\":\"cmc stations\",\"main\":{\"temp\":303.15,\"pressure\":1008,\"humidity\":74,\"temp_min\":303.15,\"temp_max\":303.15},\"wind\":{\"speed\":3.1,\"deg\":320},\"clouds\":{\"all\":75},\"dt\":1458518400,\"sys\":{\"type\":1,\"id\":8166,\"message\":0.0025,\"country\":\"AU\",\"sunrise\":1458505258,\"sunset\":1458548812},\"id\":2172797,\"name\":\"Cairns\",\"cod\":200}"
This is stopping my over service using (SwiftJSON) detecting this as valid JSON.
Can anyone tell me how to make the API information come out as correctly formatted JSON?
I tried .replace like so:
res.on('end', function() {
result = body.replace('\\', '');
context.succeed(result);
});
It did not change anything. Still had the same output.
You're posting it as a string.
Try context.succeed(JSON.parse(result))
From the docs
The result provided must be JSON.stringify compatible. If AWS Lambda fails to stringify or encounters another error, an unhandled exception is thrown, with the X-Amz-Function-Error response header set to Unhandled.
http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
So essentially it's taking your json string as a string and calling JSON.stringify on it...thus escaping all the quotes as you're seeing. Pass the parsed JSON object to succeed and it should not have this issue
In case of Java, just return a JSONObject. Looks like when returning string it is trying to do some transformation and ends up escaping all the quotes.
If using Java, the response can be a user defined object as below
class Handler implements RequestHandler<SQSEvent, CustomObject> {
public CustomObject handleRequest(SQSEvent event, Context context) {
return new CustomObject();
}
}
Sample code can be found here.
Do this on your result: response.json()
You can use:
res.on('end', function() {
context.succeed(body.replace(/\\/g, '') );
To replace \ with nothing..

accessing dynamic property when calling Action....MVC

I have an Action method that returns JSON, for brevity, I excluded code. :
public ActionResult SetMasterLocation(string masterValue)
{
json = new JavaScriptSerializer().Serialize(masterLocation);
return Json(json, JsonRequestBehavior.AllowGet);
}
I need to call this method and access the JSON string that gets returned:
var jVendors = SetMasterLocation(masterValue);
When I run it and inspect the output, I see the JSON string in a dynamic property called Data:
But if I try to access data like this, the app will not compile because the compiler says Cannot resolve symbol 'Data':
var jVendors = SetMasterLocation(masterValue);
var data = jVendors.Data;
How do I access the Data property at runtime?
Return JsonResult
return new JsonResult()
{
Data = someData,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
Then, you can access Data property of the result

Can i return a Partial view and a Json object from my action method at the same time

i have the following action method, that returns a partial view _create. but is there a way to pass a Json object such as return Json(new { IsSuccess = "True" }, with the Partial view.
My Action method looks as follow:-
try
{
if (ModelState.IsValid)
{
var v = repository.GetVisit(visitid);
if (!(v.EligableToStart(User.Identity.Name)))
{
return View("NotFound");
}
vlr.VisitID = visitid;
repository.AddVisitLabResult(vlr);
repository.Save();
ViewBag.LabTestID = new SelectList(repository.FindAllLabTest(), "LabTestID", "Description", vlr.LabTestID);
// return Json(new { IsSuccess = "True" }, JsonRequestBehavior.AllowGet);
#ViewBag.status = "Added Succsfully";
return PartialView("_create",vlr) ;
}
}
::-UPDATED-::
what i am trying to do as follow:-
i am calling the action method using ajax.beginform
using (Ajax.BeginForm("CreateAll", "VisitLabResult", new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = item.ToString(),
InsertionMode = InsertionMode.Replace,
OnSuccess = string.Format("disableform({0})", Json.Encode(item)),
}))
after successfully receiving the response from the server ,, the Onsuccess script will be executed,,, the script simply disable the form:-
function disableform(id) {
$('#' + id + ' :input').prop("disabled", true);
}
The problem is that the script will always disable the form even is some validation error occurs,, so what i was trying to achieve is to return a JSON with the partial view that indicate if the ModelState.IsValid was valid or not,, and if it was not valid to keep the form enabled to allow the user to correct the validation errors.
BR
You can return ONLY ONE view from action method, if at all you want to pass other information,make use of ViewData or ViewBag
ViewBag.IsSuccess = "True";
Or
ViewData["IsSuccess"] = "True";
No, you can return only the view and pass JSON as the model, or ViewBag (I recommend model.)
Why not simply extend the model that you are already passing to the View adding the property IsSuccess?
ViewBag or ViewData are evil in my opinion. Try to always use a ViewModel when returning data to the view.
In such cases I used following solution:
In your ajax form definition set:
OnComplete = "yourCallback"
Then:
yourCallback = function(response){
var json = response.responseJSON;
if(json.success){
alert('Well done!');
} else {
var form = $('#formId');
form.html(json.html);
form.removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
}
}
Your controller should return something like this:
var result = new { success = false, html = helper.Partial("_YourPartial", model) };
return Json(result);
Where helper helps you to add validation to your partial view. (Described here: https://stackoverflow.com/a/4270511/952023)