How to clarify existing json data using asp.net - c#

Below is my JSON data that generated somehow :
[
{
id: "1926d769-319b-41ec-8bba-deabbcc44992",
start: "2014-09-02T11:00:00",
end: "2014-09-02T12:00:00",
title: ""ATR" Recieved by Lender - First",
body: ""ATR" Recieved by Lender - First",
color: "",
editable: false,
officeEvent: false,
allDay: false
},
{
id: "37e65cc0-a44a-460d-acc6-f8847fcdc384",
start: "2014-08-04T12:00:00",
end: "2014-08-04T13:00:00",
title: "Sign Disclosures",
body: "Sign Disclosures",
color: "",
editable: false,
officeEvent: false,
allDay: false
}
]
The first item title and body contain double quote(""), So that the JSON data showing an error. Now how can i escape this quote from whole JSON data at the same time like below.
title: "\"ATR\" Recieved by Lender - First"
How can i achieve this in Asp.Net C#?

Brian is correct you really need to talk to the vendor and have them fix their data / code. For the work around without using a loop though you can use strings replace method to get the clean the JOSN.
string cleanJson = source.toString();
string cleanJson = cleanJson.Replace("title: \"\"", "title: \"\\\"");
string cleanJson = cleanJson.Replace("body: \"\"", "title: \"\\\"");
return convertBackToJson(cleanJson);
If you don't want to use a loop for performance reasons this may not be a better solution. if you are looking to speed up the processes up consider trying to break up your JSON into pieces if you can isolate the bogus records clean them and append them into the final output.

Related

How can i save a bool value as 0 or 1 to database in a json body?

I have an endpoint as follows:
https://myapi/user/1234
the body is
{
"ExpiryDays": "50",
"Access1": "False",
"Access2": "True",
"Access3": "False",
"Address": "500",
}
In the database the columns and datatype are
ExpiryDays int
Access1 bit, not null
Access2 bit, not null
Access3 bit, not null
Address nvarchar(max)
I would have though the False would be converted to a 0 and True to 1 when inserted in the db.
In my model in MVC I have defined the fields as bool.
But i get the error
The JSON value could not be converted to System.Nullable`1[System.Boolean]. Path: $.Access1 .
Any ideas as on this ?
See this - bool should have no quotes. Ideally, it should be in lower case but I don't think it cares that much. You can also use 0 and 1 I think
Also assuming "ExpiryDays" is a number it shouldn't really be quoted either.
Try changing the body to:
{
"ExpiryDays": 50,
"Access1": False,
"Access2": True,
"Access3": False,
"Address": "500",
}
try deleting the quotes
for example "Access1": False,

Can't parse json into JArray object after using JSON_ARRAY and JSON_OBJECT in mysql

I'm querying a mySQL (MariaDB) database and use JSON_ARRAY and JSON_OBJECT to gather json objects as array.
I have an api to retrieve the data from the DB, by using GetAsync.
Afterwards, in the api consumer, I want to parse the Json into an object,
using JArray (Newtonsoft).
I can't manage to parse the Json due to problem in the JSON_OBJECT (it seems like a quote wrapping the array sign "["). See error code below.
What am I doing wrong and how can I fix it ?
When getting another Json from another data source (not using JSON_ARRAY and JSON_OBJECT), parsing is working (see example below)
This is my code:
public JARrray parse(HttpResponseMessage response)
{
return JArray.Parse(response.Content.ReadAsStringAsync().Result);
}
This is the string that works:
[
{
"remark":"",
"driver": [
{
"username":"0000000",
"uid":"00000000",
"fname": "000000",
"lname": ""
}
]
}
]
And this is the string that get the message
After parsing a value an unexpected character was encountered: u. Path '[0].driver', line..."
I can see in the stack that this is happening on the line:
JsonTextReader.ParsePostValue(Boolean ignoreComments):
Json:
[
{
"remark":"",
"driver": "[{\"username\": \"0000000\", \"uid\": \"00000000\", \"fname\":\"ZZZZZ\", \"lname\":\"\"}]"
}
]
or even, when I removing the "" :
[
{
"remark":"",
"driver": "[{"username": "0000000", "uid": "00000000", "fname":"ZZZZZ", "lname":""}]"
}
]
\"fname\":"\ZZZZZ\"
The escaped double quote in front of ZZZZZ is wrong. Change it from "\ to \".

LuisRecognizer result doesn't show " Value " field in DateTimeV2 resolution Json

I am trying to extract dateTime using LUIS.
Environment: BotFramework V4
Lang: c#/ .NET
I am using the built in recognizer to extract Date / Time provided by the user.
var recognizerResult = await_services.LuisServices[LuisKey].RecognizeAsync(turnContext, cancellationToken);
Newtonsoft.Json.Linq.JObject Entities1 = recognizerResult?.Entities;
Now when I am printing this JSON file I am not getting the " Value " field in the Resolution portion.This is the JSON response I am getting when i extract the entities.
Query String : fly on 20 mar return on 24 mar Entities Returned { "$instance": { “datetime”: [ { “startIndex”: 7, “endIndex”: 13, “text”: “20 mar”, “type”: “builtin.datetimeV2.date” }, { “startIndex”: 24, “endIndex”: 30, “text”: “24 mar”, “type”: “builtin.datetimeV2.date” } ] }, “datetime”: [ { “type”: “date”, “timex”: [ “XXXX-03-20” ] }, { “type”: “date”, “timex”: [ “XXXX-03-24” ] } ] }
I have tried using the includeAPIResult : true parameter when creating the recognizer. Still the same results. Kindly suggest what am I doing wrong.
And how can I extract proper Date time from the json response.
Yeah so this is an known issue right now if you choose to use the LuisRecognizer package. Essentially it "eats" important details of the raw LUIS response.
My professional recommendation would be to eschew LuisRecognizer and just use the full on LuisClient directly. The only real reason to use LuisRecognizer is if you want that extra level of abstraction that allows you to work with other recognizer implementations. If you're "all in" on LUIS, then you probably want access to the full fidelity of LUIS anyway.
I do something like this:
luisResults.Entities.MyDateEntity?[0].Expressions?[0]
It will then result to a string that I parse to dateTime. Given that luis successfully sets MyDateEntity value.

Newtonsoft.Json - Unexpected characters while parsing value

I'm pulling intents back from API.AI and parsing these to C# objects using Newtonsoft.Json in the following way:-
intentListModel = JsonConvert.DeserializeObject<List<IntentListModel>>(intentList);
intentList is a JSON string from the webrequest. However at Line 1, position 161, it fails. The bit of JSON concerned is:-
"contextIn": [
"Employed"
],
"events": [{
"name": "Occupation_DOB"
}],
NB: This is only part of the JSON, and the JSON opens and closes with [] as it is a list of JSON items.
specifically the opening { on events. I'm stumped, I've run it through a validator and I see valid JSON.
Could anyone suggest what I can try, or is there a setting somewhere for this? Or is the error message actually looking another area of the JSON string?
Thanks in advance!
UPDATE
Whole JSON sample posted
[
{
"id":"18b025c5-3567-49c1-a9e9-25583f9156ca",
"name":"IncomeProtection - Employed? - Occupation/DOB/Email",
"state":"LOADED",
"contextIn":[
"Employed"
],
"events":[
{
"name":"Occupation_DOB"
}
],
"parentId":"ad5f0007-c084-4615-93dd-6c82ca5e7602",
"parameters":[
{
"required":true,
"dataType":"#Occupation",
"name":"Occupation",
"value":"$Occupation",
"prompts":[
"Whatu0027s your Occupation?"
],
"isList":false
},
{
"required":true,
"dataType":"#sys.date",
"name":"date",
"value":"$date",
"prompts":[
"Whatu0027s your date of birth?"
],
"isList":false
}
],
"contextOut":[
{
"name":"OccupationDOB",
"parameters":{
},
"lifespan":1
}
],
"actions":[
"IncomeProtection:Occupation/DOB"
],
"priority":500000,
"fallbackIntent":false
}
]
This issue was down to one of the items from the API being returned in a list, but in the particular example I looked at, the API returned a list of 1 item. I misread the brackets and created a class property of type string instead of List<string>, hence the failure of code.
Hope this helps people in the future.

Split a string at the first occurrence of a character after matching string

The Data:
{
\"value\": 17.11, \"year\": 2015, \"sub\": [ {\"x\": 0, \"y\": 0.94 }, {\"x\": 1, \"y\": 1.08 }]
}
,
{
\"value\": 17.23, \"year\": 2015, \"sub\": [ {\"x\": 0, \"y\": 0.23 }, {\"x\": 1, \"y\": 1.22 }]
}
I've got a list of JSON objects in a format you see above and I need to split the objects at the ',' between the two objects. The problem is that there are other commas present in the file. Apart from actually serializing the JSON into a List, is there any other way to get this done?
I'm trying to get the data into a string array like:
string[] split = json.split(',');
Note that the data above is actually all coming on one line, there aren't any line breaks, tabs, or anything. I organized it above to make it more readable.
Writing your own parser would be tricky. It would be much easier if you used a JSON parser. Your format is not valid JSON, but it would be with surrounding []. So if you insert those characters, you should be able to use a real parser:
using Newtonsoft.Json
// ...
var objects = JsonConvert.DeserializeObject<List<SomeClass>>("[" + json + "]");

Categories

Resources