Parsing JSON in C# - 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 %>')

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']);
}
}

Select type object from json?

I have a problem with correct parse object from json query. I read something about JObject. Now i have two Model for example like Car and MotorBike. Query result is:
"Vehicles":
[
{
"Id": 1,
"title": "test",
"price": "4000",
"type": "Car"
},
{
"Id": 1,
"title": "test",
"price": "4000",
"drivingLicenseCat" "A",
"type": "MotorBike"
}
]
how can i parse to custom model by type
How much control over the JSON do you have? If you are generating the JSON out of, say, web api correctly, it would come through more like:
"Vehicles":
[
{
"Id": 1,
"title": "test",
"price": "4000",
"$type": "YourNamespace.Car, YourNamespace"
},
{
"Id": 1,
"title": "test",
"price": "4000",
"drivingLicenseCat" "A",
"$type": "YourNamespace.MotorBike, YourNamespace"
}
]
and then it would be automatically deserialized when you bring it in...
Ensure, in the model that you are serializing and sending out as JSON, that you mark it up like so:
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]
This will add the type names to the objects as they are serialized. I should also note, that this is with Newtonsoft as your Json library. I'm not sure about the built-in Json.

Deserializing random json file in c#

i am trying to take in a json file and iterate over some of the values.
The file is 73000 lines long, and i only need a few values.
Here is an example of the json file:
{
"value" : "key"
"value" : "key"
"Owner": {
"UserId": xxx,
"Username": "xxx",
},
"Items": [
{
"value": "key",
"value": "key",
"Comment": "",
"value": {
"value": {
"value": "key",
"value": "key",
"value": "key",
}
},
"CustomFields": [
{
"Name": "something",
"Content": "true"
}
]
}
]
}
How do i load this in without defining the object? i need 5 values per item, from different nesting levels, though i dont want to define the class as the file is more than 70.000 lines.
I tried doing it like this:
var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
But that way i will get an error when i try to itterate over items, as items value will now be a string!
foreach (Dictionary<string, string> result in values["items"])
Is there a way to load the file, defining the class based on the json schema?
I need values from different levels in the file, some at root level some nested.

How to convert List<ClassModel> to List<string> easily

I have an ASP.NET Core 3.1 WebAPI which contains a class model called ImagePath that has one property only called filename, my problem is how can I convert or map a list of this class to list of string.. I mean it takes the property filename and add it to a list of string BUT without using any kind of loops (for, foreach, while..)
The data that comes from the API
"images": [
{
"filename": "6f2290d2-c26f-4132-b7dc-c70ca3bbadb5.jpg"
},
{
"filename": "8057c245-d980-40b5-964e-5fda69684300.jpg"
},
{
"filename": "a085f172-e711-4520-abab-1defc8e9dde8.jpg"
},
{
"filename": "db5c2296-0679-4e02-9e34-674aaa578be8.jpg"
}
],
what I want is this
"images": [
"6f2290d2-c26f-4132-b7dc-c70ca3bbadb5.jpg",
"8057c245-d980-40b5-964e-5fda69684300.jpg",
"a085f172-e711-4520-abab-1defc8e9dde8.jpg",
"db5c2296-0679-4e02-9e34-674aaa578be8.jpg"
],
Any solutions?
listClassModel.Select(p => p.filename).ToList()

Json Object parse error

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\"}";

Categories

Resources