Json Object parse error - c#

I am storing data in my cassandra database as string and i want to retrieve the string and convert it into json. i get an exception saying
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' happened
is there something wrong with the data stored ? or i am doing some other thing wrong ?
My query is :
INSERT INTO table2(key1,col1) values ('5',{'url':'{"hello":
{"hi":{"hey":"1","time":"5"}},
{"reg":{"hey":"1","time":"1"}},
{"install":{"hey":"0"}}},
"task":"1","retry":"00",
"max":"5","call":"140"'});
In my db when i click the map<text,text> column, it gets stored as :
{\"hello\":\r\n
{\"subscription_atrisk\":{\"hey\":\"1\",\"time\":\"100\"}},
{\"reg\":{\"hey\":\"1\",\"time\":\"2000\"}},
\"task\":\"0\",\"retry\":\"300\",\"max\":\"5\",\"call\":\"14400\"}
in my c# code, i try
string s = "{\"hello\":\r\n {\"subscription_atrisk\":{\"hey\":\"1\",\"time\":\"100\"}},{\"reg\":{\"hey\":\"1\",\"time\":\"2000\"}},\"task\":\"0\",\"retry\":\"300\",\"max\":\"5\",\"call\":\"14400\"";
Jobject json = Jobject.Parse(s); //Get an Error here.
Could anyone please throw some light on this ?

In JSON, an object should contain a key and either a value or another object/array.
You have syntax errors in your JSON object. First of all, always use double quotes.
Then... The url object has a key Hello but then where you are supposed to place two more keys, you're just putting there two more objects, as if it was an array.
This could be a correct syntax:
{
"url": {
"hello": {
"hi": {
"hey": "1",
"time": "5"
}
},
"MissingKey1":{
"reg": {
"hey": "1",
"time": "1"
}
},
"MissingKey2":{
"install": {
"hey": "0"
}
}
},
"task": "1",
"retry": "00",
"max": "5",
"call": "140"
}
Or if you really meant to have a hello object and an array of two more objects inside url:
{
"url": {
"hello": {
"hi": {
"hey": "1",
"time": "5"
}
},
"AnArray": [{
"reg": {
"hey": "1",
"time": "1"
}
}, {
"install": {
"hey": "0"
}
}]
},
"task": "1",
"retry": "00",
"max": "5",
"call": "140"
}
I suggest that before you store those JSON objects in the database, ALWAYS validate them to make sure that they're valid of syntax.
Or even better: this Newtonsoft library provides functions which serializes(creates) JSON strings from other objects. See JsonConvert.SerializeObject Method
In general it is a good idea to look around in the API documentation, it really can save you a lot of time so that you don't have to do unnecessary work.

Looks like you're missing a closing }
Try:
string s = "{\"hello\": {\"subscription_atrisk\":{\"hey\":\"1\",\"time\":\"100\"}}, \"missing_key\": {\"reg\":{\"hey\":\"1\",\"time\":\"2000\"}},\"task\":\"0\",\"retry\":\"300\",\"max\":\"5\",\"call\":\"14400\"}";

Related

JSON extract date from matching string

I am entirely new to JSON, and haven't got any familiarity with it at all. I'm tinkering around with some JSON data extracts to get a feel for it.
Currently, I have a chat export which has a large number of keys. Within these keys are a "date" key, and a "from_id" key.
I would like to search a JSON file for a matching value on the "from_id" key, and return all the values against the "date" keys with a matching "from_id" value.
For example:
{
"name": "FooBar Chat Group",
"type": "textchat",
"id": 123456789,
"messages": [
{
{
"id": 252930,
"type": "message",
"date": "2021-03-03T01:39:30",
"date_unixtime": "1614735570",
"from": "Person1",
"from_id": "user1234",
"text": "This is a message!"
},
{
"id": 252931,
"type": "message",
"date": "2021-03-03T01:41:03",
"date_unixtime": "1614735663",
"from": "Person2",
"from_id": "user9876",
"text": "This is a reply!"
},
{
"id": 252932,
"type": "message",
"date": "2021-03-03T01:42:01",
"date_unixtime": "1614735721",
"from": "Person2",
"from_id": "user9876",
"text": "This is some other text!"
},
{
"id": 252933,
"type": "message",
"date": "2021-03-03T01:42:44",
"date_unixtime": "1614735764",
"from": "Person1",
"from_id": "user1234",
"text": "Yeah, indeed it is!"
}
]
}
I want to search from_id "user1234", and for it to return the following:
2021-03-03T01:39:30
2021-03-03T01:42:44
These are the two dates that have a matching from_id.
How would I go about doing something like this, please?
I am entirely new to this, so a super basic explanation with resources would really be appreciated. Thanks!
you can try this c# code. At first you have to parse your json strig to create an object from string. Then you can use LINQ to get the data you need
using Newtonsoft.Json;
JArray messages = (JArray) JObject.Parse(json)["messages"];
string from_id="user1234";
DateTime[] dates = messages
.Where(m=> (string) m["from_id"] ==from_id)
.Select(m => (DateTime) m["date"])
.ToArray();
Assuming your sample is part of a JSON Array - starts with [ and ends with ] - you should be able to iterate and conditionally select what you want.
In javascript, you can use a for of to iterate through and an if to match your request:
for(let item of array){
if(item['from_id'] == 'user1234')
console.log(item.date);
}
As we don't know the language you're actually using, a more wide code version of it could be something like:
for(let i=0;i < array.length; i++){
if(array[i]['from_id'] == 'user1234'){
print(array[i]['date']);
}
}

.net Core & Swashbuckle/Swagger: How to provide raw json example?

I have a WebAPI controller with an operation returning a JSON schema. This JSON return value cannot be created by serializiation, so I designed the operation method as follow:
[HttpGet("{serviceName}/contract")]
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(object))]
public IActionResult GetContract(string serviceName)
{
return Content("{ \"type\": \"object\" }", "application/json"); // for example ...
}
Now I like to have a or some documented return values for Swagger. But I'm unable to do that. There is the SwaggerRequestExample attribute, but as said before, this requires a return type which in my case is not applicable.
Basically I search for a way of something like that (just dynamic):
[SwaggerResponseExample((int)HttpStatusCode.OK, "{\"anyJson\": \"Yes, I am!\"}")]
Or of course, even better like that:
[SwaggerResponseExample((int)HttpStatusCode.OK, RawJsonFabricType="TypeName", RawJsonStaticMethod="MethodName")]
Use case: The JSON schemas I need to return in operation method are stored in a database and are not created within the program code itself.
A concrete example of such a JSON schema value is:
{
"$id": "https://example.com/person.schema.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"lastName": {
"type": "string",
"description": "The person's last name."
},
"age": {
"description": "Age in years which must be equal to or greater than zero.",
"type": "integer",
"minimum": 0
}
}
}
Help will be very appreciated.
Thanks!
I'm using c#.net core 6.
Afer trying arround I came to the solution:
First: Add ExampleProvider and use generic type JsonDocument (from System.Text.Json):
public class ServiceDemandContractExampleProvider : IExamplesProvider<JsonDocument>
{
/// <inheritdoc/>
public JsonDocument GetExamples()
{
var jsonToShow = JsonDocument.Parse(#"{
""$id"": ""https://example.com/person.schema.json"",
""$schema"": ""https://json-schema.org/draft/2020-12/schema"",
""title"": ""Person"",
""type"": ""object"",
""properties"": {
""firstName"": {
""type"": ""string"",
""description"": ""The person's first name.""
},
""lastName"": {
""type"": ""string"",
""description"": ""The person's last name.""
},
""age"": {
""description"": ""Age in years which must be equal to or greater than zero."",
""type"": ""integer"",
""minimum"": 0
}
}
}");
return jsonToShow;
}
}
To JsonDocument.Parse put whatever JSON (in my case loaded content from database).
Then add the follow attributes to the operation method:
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(object))]
[SwaggerResponseExample((int)HttpStatusCode.OK, typeof(ServiceDemandContractExampleProvider))]
And it works:

Filter parsed JSON object

I am making rest call and receving following JSON response:
{
"issues": [{
"id": "250271",
"self": "KeyUrl1",
"key": "Key-8622",
"fields": {
"attachment": [{
"self": "AttachmentUrl1",
"id": "106198",
"filename": "export.htm"
}
],
"customfield_11041": "Test"
}
},
{
"id": "250272",
"self": "KeyUrl2",
"key": "Key-8621",
"fields": {
"attachment": [{
"self": "AttachmentUrl2",
"id": "106199",
"filename": "lmn.htm"
}
],
"customfield_11041": "Test"
}
},
]
}
I parsed it using NewtonSoft Json to JObject.
var jObject = JObject.Parse(response);
Further I am trying to filter such records where either attachment is missing or none of the attachments contain filename like "export".
Following is the code I have written, ideally it should result in just 1 record in the records object, however its returning both the objects.
var issues = jObject["issues"] as JArray;
var records = issues.Where(x => !x["fields"]["attachment"].Any() || !x["fields"]["attachment"].Any(y => y["filename"].Contains("export")));
Need help to figure out whats going wrong.
Here's fiddle link - https://dotnetfiddle.net/AVyIHr
The problem is that you're calling Contains("export") on the result of y["filename"], which isn't a string - it's a JToken. You need to convert to a string first, to use the form of Contains that you're expecting.
Additionally, you can get rid of the first condition - an issue with no attachments doesn't have any attachments with "export" filename anyway.
That leaves this:
var records = issues
.Where(x => !x["fields"]["attachment"].Any(y => ((string) y["filename"]).Contains("export")))
.ToList();
You may well find it's simpler to deserialize to a class, however - that will reduce the risk of typos and the risk of this sort of conversion error. If you deserialized to a List<Issue> you'd have a condition of:
x => !x.Fields.Attachments.Any(y => y.Filename.Contains("export"))
... which I think is rather cleaner.
var records = issues.Where(x => !x["fields"]["attachment"].Any() || !x["fields"]["attachment"].Any(y => y["filename"].ToString().Contains("export"))).ToList();
Add .ToString() will resolve the issue.

Extract first set of records in JSON C#

I have a requirement to get the first set of records in c# JSON. Here is my JSON data for example
string sJSON = "{
{
"ID": "1",
"Name":"John",
"Area": "Java" ,
"ID": "2",
"Name": "Matt",
"Area": "Oracle" ,
"ID": "3","Name":
"Danny","Area": "Android"
}
}"
I need to extract only the 1st set of records (i.e. {{"ID": "1", "Name":"John", "Area": "Java"}}).
If there is only one record my code (see below) works fine but when there are multiple records it takes the last set of JSON data (i.e. {{"ID": "3","Name": "Danny","Area": "Android"}}).
JObject jsonObject = JObject.Parse(sJSON);
string sID = (string)jsonObject["ID"];
string sName = (string)jsonObject["Name"];
string sArea = (string)jsonObject["Area"];
Can anyone help me extract only the 1st set of JSON data?
You return the JSON data as JSON Array, now it is a simple JSON string.
If you're able to generate like below then you can easily get the single JSON element easily.
[{ "ID": "1", "Name":"John", "Area": "Java" },{ "ID": "2","Name": "Matt","Area": "Oracle" },{ "ID": "3","Name": "Danny","Area": "Android" } ]
Use the below link, to understand this JSON format.
http://json.parser.online.fr/
Parse the data as JToken.
Such that you have something like:
var jToken = JToken.Parse(sJSON);
var isEnumerable = jToken.IsEnumerable()
if(isEnumeable)
{
cast as JArray and get firstOrdefault
}
var isObject = jToken.IsObject();
if(isObject )
{
cast as JObject and perform straight casting
}

Parsing JSON in C#

I have a JSON string that I am sending to a c# server. It comprises an array of Event objects and an Array of relationship objects. The relationship objects describe the database table relationships.
However I'm having trouble getting data from the the JSON at the server. The object doesn't exist on the server to deserailize into and JSON.net throws parse errors when I try the following:
// Both throw parse errors
JObject o = JObject.Parse(Request.Form.ToString());
JsonConvert.DeserializeObject<MobileEvents>(Request.Form.ToString());
the JSON:
{
"CreateEvents": {
"Event": [
{
"Id": "1",
"Subject": "Hire a Clown"
}
],
"Relationship": [
{
"Primary": "Table1",
"Secondary": "Table2",
"Field": [
{
"Table1Id": "1",
"Table2Id": [
"101"
]
}
]
},
{
"Primary": "Table1",
"Secondary": "Table3",
"Field": [
{
"Table1Id": "1",
"Table3Id": [
"200025"
]
}
]
},
{
"Primary": "Table1",
"Secondary": "Table4",
"Field": [
{
"Table1Id": "1",
"Table4Id": [
"3"
]
}
]
}
]
}
}
Request.Form.ToString() would returns the result like "a=1&b=3", it's definitely not what you need.
If you're passing values as submiting a form, you can use Request.Form["your-key"] to get the value.
If you're passing values by the http body, you can use new StreamReader(Request.InputStream).ReadToEnd() to get the whole JSON string.
I think you have an error within your getting ...
It's not
this.Request.Form.ToString(); // see http://stackoverflow.com/questions/7065979/why-is-the-return-value-of-request-form-tostring-different-from-the-result-of for output
Instead it should be
this.Request.Form["myInputNAME"].ToString();
Important - really use the name-attribute of your input/select/...-element
Anyways: I would like to encourage you, to use eg. <asp:HiddenField runat="server" ID="foo" />. When you have a server-control you can then access its value by simple doing this.foo.Value at server-side, whereas at client-side you can access the input field like document.getElementById('<%= this.foo.ClientID %>')

Categories

Resources