I was able to solve this solution is in the coment
I have problem with parsing data that I get rom Facebook on appRequestCallback.
The request is send and that part is ok. But I need to pars the send data for the internal uses.
the code is this
private void appRequestCallback(FBResult result)
{
Util.Log("appRequestCallback");
if (result != null)
{
var responseObject = Json.Deserialize(result.Text) as Dictionary<string, object>;
object obj = 0;
string resp = (string)responseObject["request"];
Util.Log ("resp : " + resp);
if (responseObject.TryGetValue("cancelled", out obj))
{
Util.Log("Request cancelled");
}
else if (responseObject.TryGetValue("request", out obj))
{
responseObject.TryGetValue("to", out obj);
string[] s = (string[]) obj;
Util.Log ("s: " + s);
AddPopupMessage("Request Sent", ChallengeDisplayTime);
Util.Log("Request sent");
}
}
}
In the console I get this
appRequestCallback
UnityEngine.Debug:Log(Object)
resp: 870884436303337
UnityEngine.Debug:Log(Object)
And then the error
InvalidCastException: Cannot cast from source type to destination type.
MainMenu.appRequestCallback (.FBResult result) (at Assets/Resources/Scripts/MainMenu.cs:482)
Facebook.AsyncRequestDialogPost.CallbackWithErrorHandling (.FBResult result)
Facebook.AsyncRequestString+c__Iterator0.MoveNext ()
The problem is in parsing of to: part of json file and I am not sure why. I have tried to cast it into string, string[], List<>, Array, ArrayList. As I see the problem is that I am not using the good cast type for the to: but I can not figure out what the correct cast type is
Related
We want to get the UserName from the ServiceStack session, but we find that the backslashes in the UserName are not deserialized as expected. The UserName has this format 'domainname\username' and serialized in a jwt token this looks like:
{
"typ": "JWT",
"alg": "HS256"
}.{
"iss": "ssjwt",
"iat": 1635952233,
"exp": 1635955833,
"name": "Robin Doe",
"preferred_username": "domainname\\robindoe"
}.[Signature]
After calling:
var sessionFromJwt = JwtAuthProviderReader.CreateSessionFromJwt(req);
userName = sessionFromJwt.UserName;
The userName variable contains the value 'domainname\\robindoe' instead of 'domainname\robindoe'.
After digging in the ServiceStack code, we pin this down to the PopulateFromMap() method in https://github.com/ServiceStack/ServiceStack/blob/36df74a8b1ba7bf06f85262c1155e1425c082906/src/ServiceStack/Auth/UserAuth.cs#L388.
To demonstrate this problem we have written a small program to prove the point:
class Program
{
static void Main(string[] args)
{
var jwtPayload = JsonObject.Parse(#"{
""iss"": ""ssjwt"",
""iat"": 1635952233,
""exp"": 1635955833,
""name"": ""John Doe"",
""preferred_username"": ""domainname\\username""
}");
var session = new AuthUserSession();
// The PopulateFromMap implementation does not deserialize the json values according to json standards
UserAuthExtensions.PopulateFromMap(session, jwtPayload);
// Notice that the session.UserName still has the escape character 'domainname\\username' instead of the expected 'domainname\username'
Console.WriteLine(session.UserName);
// The PopulateFromMap should deserialize also the values, like in test Can_dynamically_parse_JSON_with_escape_chars()
Can_dynamically_parse_JSON_with_escape_chars();
}
private const string JsonCentroid = #"{""place"":{ ""woeid"":12345, ""placeTypeName"":""St\\a\/te"" } }";
// Source: https://github.com/ServiceStack/ServiceStack.Text/blob/master/tests/ServiceStack.Text.Tests/JsonObjectTests.cs
public static void Can_dynamically_parse_JSON_with_escape_chars()
{
var placeTypeName = JsonObject.Parse(JsonCentroid).Object("place").Get("placeTypeName");
if (placeTypeName != "St\\a/te")
throw new InvalidCastException(placeTypeName + " != St\\a/te");
placeTypeName = JsonObject.Parse(JsonCentroid).Object("place").Get<string>("placeTypeName");
if (placeTypeName != "St\\a/te")
throw new InvalidCastException(placeTypeName + " != St\\a/te");
}
}
Why does UserAuthExtensions.PopulateFromMap(session, jwtPayload) does not deserialize json values with escape correctly in ServiceStack.Auth?
The issue is due to enumerating a JsonObject didn't return the same escaped string value as indexing it which has been resolved from this commit.
This change is available from v5.12.1+ that's now available on MyGet.
I'm using asyncHTTPrequest for async request to a REST API in ESP8266.
I receive the response in JSON format but can't parse it.
This kind of parsing was working while i used to made sync call to API.
I tried to store the request->responseText() into a String variable because its return a String, but the variable never get any value.
void sendRequest() {
if (request.readyState() == 0 || request.readyState() == 4) {
request.open("GET", "http://192.168.1.103:45456/api/systems/1013/arduino");
request.send();
}
}
void requestCB(void* optParm, asyncHTTPrequest* request, int readyState) {
if (readyState == 4) {
Serial.println(request->responseText());
const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(2) + 2*JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(8)+816;
DynamicJsonBuffer jsonBuffer(capacity);
JsonObject& root = jsonBuffer.parseObject(request->responseText());
String a = request->responseText();
Serial.println(a);
JsonObject& schState = root["dataForArduino"][0];
String beginTime = schState["start"]; // "2019-12-02T21:51:00"
}
}
void setup() {
Serial.begin(9600);
wifi.Connect();
request.onReadyStateChange(requestCB);
ticker.attach(5, sendRequest);
}
I have wrote json parsing function (__get_from_json) to get key value from json here
e.g. if you have json response like
{
"timestamp" : "2020-04-01 19:20:49"
}
and in your application you want to parse timestamp value from it then
char response[max_response_size] = "{ \"timestamp\" : \"2020-04-01 19:20:49\" }";
char key[max_key_size] = "timestamp";
char value[max_value_size] = "";
if( __get_from_json( response, key, value, max_value_size ) ){
Serial.println(value);
}
I had the same problem and added .c_str() to get the response to print.
So in your example it would be:
String a = request->responseText();
Serial.println(a.c_str());
For the JSON I also needed to add .c_str()
DynamicJsonDocument jsonDoc(2048);
DeserializeJson(jsonDoc, a.c_str());
I am using aws_ai plugin and the response is in the form of
instance of Future<String>
I read the response as given below. I need to access specific value from json with key "confidence", how do I access it?
Future main1() async {
File sourceImagefile; //load source image in this File object
String accessKey = "",
secretKey = "",
region = "" ;
RekognitionHandler rekognition = new RekognitionHandler(accessKey, secretKey, region);
if(sourceImagefile !=null && targetImagefile !=null) {
Future<String> labelsArray = rekognition.compareFaces(
sourceImagefile, targetImagefile);
print(labelsArray);
return labelsArray.toString();
}else{
return "Enter Image";}
}
___________________________________
(later in widget build:)
___________________________________
onpressed(){
main1().then((labelsArray){
print("json value is: "+labelsArray);
});
}
the current result is :
json value is: Instance of 'Future<String>'
thanks for the help!
The reason you are getting the Instance of 'Future<String>' as a result is you are not waiting for the future to return and just getting the Future<String> object back refer this for more details:
The below code should solve your problem:
Future<String> futureFunction() async {
RekognitionHandler rekognition = new RekognitionHandler(accessKey, secretKey, region);
if(sourceImagefile !=null && targetImagefile !=null) {
var labelsArray = await rekognition.compareFaces(
sourceImagefile, targetImagefile);
print(labelsArray);
return labelsArray.toString();
} else {
return "enter image";
}
}
The Nancy documentation seems to say that Pipelines.OnError should return null - as opposed to BeforeResponse which allows both null and a Response object.
All the examples like this one and many code samples here on StackOverflow show a Response being returned in the OnError, just like in the BeforeRequest.
When I attempt to return an HTTPStatus string for the Pipelines.OnError, everything works OK!
But when I attempt to return a Response, I get a compiler error:
Operator '+=' cannot be applied to operands of type 'Nancy.ErrorPipeline' and 'lambda expression'
I'm emulating almost exactly the code in the Nancy example, except for the fact that mine is a TinyIocContainer while the example's is using a StructureMap container and a StructureMap derived bootstrapper
Here's my code:
const string errKey = "My proj error";
const string creationProblem = "Message creation (HTTP-POST)";
const string retrievalProblem = "Message retrieval (HTTP-GET)";
public void Initialize(IPipelines pipelines)
{
string jsonContentType = "application/json";
byte[] jsonFailedCreate = toJsonByteArray(creationProblem);
byte[] jsonFailedRetrieve = toJsonByteArray(retrievalProblem);
Response responseFailedCreate = new Response
{
StatusCode = HttpStatusCode.NotModified,
ContentType = jsonContentType,
Contents = (stream) =>
stream.Write(jsonFailedCreate, 0, jsonFailedCreate.Length)
};
Response responseFailedRetrieve = new Response
{
StatusCode = HttpStatusCode.NotFound,
ContentType = jsonContentType,
Contents = (stream) =>
stream.Write(jsonFailedRetrieve, 0, jsonFailedRetrieve.Length)
};
// POST - error in Create call
pipelines.OnError += (context, exception) =>
{
// POST - error during Create call
if (context.Request.Method == "POST")
return responsefailedCreate;
// GET - error during Retrieve call
else if (context.Request.Method == "GET")
return responseFailedRetrieve;
// All other cases - not supported
else
return HttpStatusCode.InternalServerError;
};
}
private byte[] toJsonByteArray(string plainString)
{
string jsonString = new JObject { { errKey, plainString } }.ToString();
byte[] result = Encoding.UTF8.GetBytes(jsonString);
return result;
}
I had the same problem and I found a nice approach to the problem: http://paulstovell.com/blog/consistent-error-handling-with-nancy.
you should override RequestStartup on the Bootstrapper, here my test code:
protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
{
pipelines.OnError.AddItemToEndOfPipeline((ctx, ex) =>
{
DefaultJsonSerializer serializer = new DefaultJsonSerializer();
Response error = new JsonResponse(ex.Message,serializer);
error.StatusCode = HttpStatusCode.InternalServerError;
return error;
});
base.RequestStartup(container, pipelines, context);
}
I'm a little stumped why I can't pull the "Type" field out of my JSON stream to make a decision. It seems like this should be so easy.
I have the following JSON that I have as input:
[
{
"Institution":"ABC",
"Facility":"XYZ",
"Make":"Sunrise",
"Model":"Admission",
"SerialNumber":"",
"Revision":"1",
"Type":"ABC_Admission",
"ArchiveData":"<CSV file contents>"
}
]
In my Java I have a try-catch block with a JsonHolder class that implements Serializable to hold the JSON. Here's the Java I currently have:
try {
// Parse and split the input
JsonHolder data = JsonHolder.getField("text", input);
DataExtractor.LOG.info("JsonHolder data= " + data);
TreeNode node = data.getTreeNode();
DataExtractor.LOG.info("node size= " + node.size());
node = node.path("Type");
JsonNode json = (JsonNode) node;
DataExtractor.LOG.info("json= " + json.asText());
// code to decide what to do based on Type found
if (json.asText().equals("ABC_Admission")) {
// do one thing
} else {
// do something else
}
} catch (IOException iox) {
DataExtractor.LOG.error("Error extracting data", iox);
this.collector.fail(input);
}
When I run my code I get the following output (NOTE: I changed my package name where the class is to just for this output display)
25741 [Thread-91-DataExtractor] INFO <proprietary package name>.DataExtractor - JsonHolder data= [
{
"Institution":"ABC",
"Facility":"XYZ",
"Make":"Sunrise",
"Model":"Admission",
"SerialNumber":"",
"Revision":"1",
"Type":"ABC_Admission",
"ArchiveData":"<CSV file contents>"
}
]
25741 [Thread-91-DataExtractor] INFO <proprietary package name>.DataExtractor - node size= 1
25741 [Thread-91-DataExtractor] INFO <proprietary package name>.DataExtractor - json=
As you can see I don't get anything out. I just want to extract the value of the field "Type", so I was expecting to get the value "ABC_Admission" in this case. I would have thought the node path would separate out just that field from the rest of the JSON tree.
What am I doing wrong?
After consulting with another developer I found out the issue is my JSON is inside an array. So, I need to iterate over that array and then pull out the Type field from the object.
The updated code to resolve this is below:
try {
// Parse and split the input
JsonHolder data = JsonHolder.getField("text", input);
DataExtractor.LOG.info("JsonHolder data= " + data);
TreeNode node = data.getTreeNode();
String type = null;
// if this is an array of objects, iterate through the array
// to get the object, and reference the field we want
if (node.isArray()){
ArrayNode ary = (ArrayNode) node;
for (int i = 0; i < ary.size(); ++i) {
JsonNode obj = ary.get(i);
if (obj.has("Type")) {
type = obj.path("Type").asText();
break;
}
}
}
if (type == null) {
// Do something with failure??
}
DataExtractor.LOG.info("json= " + type);
if (type.equals("ABC_Admission")) {
// do one thing
else {
// do something else
}
} catch (IOException iox) {
DataExtractor.LOG.error("Error extracting data", iox);
this.collector.fail(input);
}