How to retreive a field from JSON string stored in database - c#

I have the following string
[{"id":"select","component":"select","editable":true,"index":2,
"label":"WHAT IS THIS QUESTION?","description":"some description",
"placeholder":"placeholder","options":["Aligator","Pikachi"],"required":false,
"validation":".*","$$hashKey":"object:38"}]
stored in the database.
I want to retrieve the validation value. How can I achieve this using LINQ? I am using EF Core 2 and I am unable to get ahead in my query.
var jsonData = from table in myRepository.Table
where table.JSONString.........
JSONString is the name of the column which stores the JSONString.
I have been searching posts on SO and on google for a while but have not found an answer yet. Thanks.
Updates:
I created classes for the JSON like the following
public class FormJson
{
[JsonProperty(PropertyName = "id")]
public string id { get; set; }
[JsonProperty(PropertyName = "component")]
public string component { get; set; }
...
}
but I still dont have a clue on how I can map this specific class to my JSON Object and get the field I need.

Download the NuGet-package Newtonsoft.Json to include using Newtonsoft.Json.Linq;
Fetch the JSON-string from your database:
var jsonStr = (from t in myRepository.Table select t.JSONString).FirstOrDefault();
Parse the JSON-string to JObject:
JObject json = JObject.Parse(jsonStr);
Read the value of a specific token you want to access:
JToken validation = json.GetValue("validation");
Do something with the value:
string value = validation.ToString();
JToken[] valueArray = validation.ToArray();
Edit:
As there is something wrong with JObject.Parse() whilst using your JSON (which is valid), instead of using JObject.Parse(), try the following:
// Add references for TextReader and JsonReader
using Newtonsoft.Json;
using System.IO;
TextReader tReader = new StringReader(jsonStr);
JsonReader jReader = new JsonTextReader(tReader);
JObject json = JObject.Load(jReader);
JToken validation = json.GetValue("validation");

Related

Advice needed to parse this JSON in .NET

Given the following JSON samples, what is the best way to parse this in c# .NET?
{"data":{"5":{"isDeleted":"false","day":"THU"}},"action":"edit"}
{"data":{"7":{"isDeleted":"false","name":"alex"}},"action":"edit"}
{"data":{"90":{"isDeleted":"true","job":"software"}},"action":"edit"}
I have looked into JSON serializing into an object but because the data could be different each time i can't map it directly to a model.
So the model for this could be
public class Record
{
public Dictionary<string, Dictionary<string, string>> Data { get; set; }
public string Action { get; set; }
}
You can deserialize the JSON into a dynamic object, which allows you to access the properties of the JSON object without having to define a specific model with JsonSerializer of System.Text.Json:
string jsonString = "{\"data\":{\"5\":{\"isDeleted\":\"false\",\"day\":\"THU\"}},\"action\":\"edit\"}";
dynamic jObject = JsonSerializer.Deserialize<dynamic>(jsonString);
string action = jObject .action;
dynamic data = jObject .data;
string isDeleted = data["5"].isDeleted;
string day = data["5"].day;

check for duplicate properties in JSON

We are working on a .Net core based web api application and for this we have a requirement to validate incoming request body which is JSON format against the c# based type.
We are at this point evaluating NJsonSchema library to see if it throws duplicate property error.
But looks like it doesnt support this validation. We also checked JSON schema validator from NewtonSoft but seems like it doesnt support duplicate property validations either.
Below is the minimized code using NJsonSchema that we use -
using NewtonSoft.Json;
public class MyRequest
{
[JsonRequired]
[JsonProperty("name")]
public string Name { get; set; }
}
and when we pass a JSON object like this -
{"name":"abc","name":"xyz"}
We need our JSON validator to throw error for duplicate property
Our example test looks like this -
[Test]
public async System.Threading.Tasks.Task SchemaValidation_WithDuplicateProperty_Async()
{
var jsonString = await File.ReadAllTextAsync("Data//JsonWithDuplicateProperty.json");
var schema = JsonSchema.FromType<MyRequest>();
var errors = schema.Validate(jsonString);
Assert.That(errors.Count(), Is.EqualTo(1));
}
So my question - Has anyone done this in the past? Or are there any libraries for .net core that provides JSON validation for duplicate properties and/or can this be done using NJsonSchema or NewtonSoft.
As #zaggler notes, using Newtonsoft, you can use the DuplicatePropertyNameHandling enum. Unfortunately, you can't use it directly in a a call to DeserializeObject (in the JsonSerializerSettings); it has to be used in a JToken Reader. See this discussion thread for more details:
https://github.com/JamesNK/Newtonsoft.Json/issues/931
Here is a method that wraps the action up in a DeserializeObject-esque way:
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
public class Program
{
public static void Main()
{
var json = #"{""name"":""abc"",""name"":""xyz""}";
var objA = DeserializeObject<MyRequest>(json, new JsonSerializerSettings(), DuplicatePropertyNameHandling.Ignore);
Console.WriteLine(".Ignore: " + objA.Name);
var objB = DeserializeObject<MyRequest>(json, new JsonSerializerSettings(), DuplicatePropertyNameHandling.Replace);
Console.WriteLine(".Replace: " + objB.Name);
var objC = DeserializeObject<MyRequest>(json, new JsonSerializerSettings(), DuplicatePropertyNameHandling.Error);
Console.WriteLine(".Error: " + objC.Name); // throws error before getting here
}
public static T DeserializeObject<T>(string json, JsonSerializerSettings settings, DuplicatePropertyNameHandling duplicateHandling)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
using (var stringReader = new StringReader(json))
using (var jsonTextReader = new JsonTextReader(stringReader))
{
jsonTextReader.DateParseHandling = DateParseHandling.None;
JsonLoadSettings loadSettings = new JsonLoadSettings {
DuplicatePropertyNameHandling = duplicateHandling
};
var jtoken = JToken.ReadFrom(jsonTextReader, loadSettings);
return jtoken.ToObject<T>(jsonSerializer);
}
}
}
public class MyRequest
{
[JsonRequired]
[JsonProperty("name")]
public string Name { get; set; }
}
Output:
.Ignore: abc
.Replace: xyz
Run-time exception (line 31): Property with
the name 'name' already exists in the current JSON object. Path
'name', line 1, position 21.
See:
https://dotnetfiddle.net/EfpzZu

How can I add json data to a label in C#? ( windows forms )

so i want to get bitcoin price from a URL and see it in a label in my form.
URL
i tried to make a class for it with the code
public string price { get; set; }
but i don't know what to do after that, i searched a lot in google but they all show the result in list and etc
To deserialize, first you need to make a class with the attributes the JSON has. This page will help you a lot in that.
Once you have a class, you need to deserialize your JSON into that class. In C# I like to use JsonConvert from the library Newtonsoft.Json, you need to import it.
The method that deserializes it is JsonConvert.DeserializeObject.
One little example, let's say your class is called Bitcoin, then you would have to do it that way :
var myBitcoin = JsonConvert.DeserializeObject<Bitcoin>(yourJson);
EDIT: To pull your json from an URL you can use Webclient DownloadString method.
var myjson = new WebClient().DownloadString("url");
This post may also help you.
This should be your class.
public class APIResponse
{
public string symbol { get; set; }
public string price { get; set; }
}
Then in your function add these lines.
APIResponse response = new APIResponse();
response = JsonConvert.DeserializeObject<APIResponse>();
myPriceLabel.Text = response.price;
What did we do? We created a C# model same as the Json Data model and we took JSON data and converted it to APIResponse type so we can access it and use it as we like.
It can be achieved simply by converting the Json with generic object
var myBitcoin = JsonConvert.DeserializeObject<object>(yourJson);
thank you all for answering but i found the solution!
the code should be like this
string url = "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT";
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString(url);
JavaScriptSerializer oJS = new JavaScriptSerializer();
PriceClass obj = new PriceClass();
obj = oJS.Deserialize<PriceClass>(json);
BTCPrice_Label.Text = obj.price;
}
and the class should be like this
using System;
public class PriceClass
{
public string symbol { get; set; }
public string price { get; set; }
}

Parsing json object in C#?

I'm using System.Net.Json.JsonTextParser to parse json files while developing program in C#, so I setup the col object like following according to the tutorial:
JsonTextParser parser = new JsonTextParser();
JsonObject obj = parser.Parse(System.IO.File.ReadAllText(file));
JsonObjectCollection col = (JsonObjectCollection)obj;
And in this case, I know I can get value of a key(for example, "formats") like following:
string Data = Convert.ToString(col["formats"].GetValue());
However, how can I read another json object under a key? Sorry I don't know how to express this, but, for example, I have:
"formats" : {"key1" : "value11", "key2" : "value12"}, {"key1" : "value21", "key2" : "value22"}
and what should I do to get each json object under "formats"? How to read each value of "key1"?
you should use https://www.nuget.org/packages/Newtonsoft.Json/
you should create a c# class coressponding your json file.
for your json file it would be:
public class Formats
{
public string Key1 {get; set;}
public string Key2 {get; set;}
}
and then convert your json file to c# objects:
using (var streamReader = new StreamReader("file.json"))
{
string json = streamReader.ReadToEnd();
var jsonObject = JsonConvert.DeserializeObject<List<Formats>>(json);
foreach( var obj in jsonObject )
{
Console.WriteLine($"Key1: {obj.Key1}, Key2: {obj.Key2}");
}
}

Loading a .json file into c# program

I am trying to move my website from XML based config files to JSON based ones. Is there a way to load in a .json file in so that it turns into the object? I have been searching the web and I cannot find one. I already have the .xml file converted and saved as a .json. I would rather not use a 3rd party library.
You really should use an established library, such as Newtonsoft.Json (which even Microsoft uses for frameworks such as MVC and WebAPI), or .NET's built-in JavascriptSerializer.
Here's a sample of reading JSON using Newtonsoft.Json:
JObject o1 = JObject.Parse(File.ReadAllText(#"c:\videogames.json"));
// read JSON directly from a file
using (StreamReader file = File.OpenText(#"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject) JToken.ReadFrom(reader);
}
Another good way to serialize json into c# is below:
RootObject ro = new RootObject();
try
{
StreamReader sr = new StreamReader(FileLoc);
string jsonString = sr.ReadToEnd();
JavaScriptSerializer ser = new JavaScriptSerializer();
ro = ser.Deserialize<RootObject>(jsonString);
}
you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client
As mentioned in the other answer I would recommend using json.NET. You can download the package using NuGet. Then to deserialize your json files into C# objects you can do something like;
JsonSerializer serializer = new JsonSerializer();
MyObject obj = serializer.Deserialize<MyObject>(File.ReadAllText(#".\path\to\json\config\file.json");
The above code assumes that you have something like
public class MyObject
{
public string prop1 { get; set; };
public string prop2 { get; set; };
}
And your json looks like;
{
"prop1":"value1",
"prop2":"value2"
}
I prefer using the generic deserialize method which will deserialize json into an object assuming that you provide it with a type who's definition matches the json's. If there are discrepancies between the two it could throw, or not set values, or just ignore things in the json, depends on what the problem is. If the json definition exactly matches the C# types definition then it just works.
Use Server.MapPath to get the actual path of the JSON file and load and read the file using StreamReader
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class RootObject
{
public string url_short { get; set; }
public string url_long { get; set; }
public int type { get; set; }
}
public class Program
{
static public void Main()
{
using (StreamReader r = new StreamReader(Server.MapPath("~/test.json")))
{
string json = r.ReadToEnd();
List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(json);
}
Console.WriteLine(ro[0].url_short);
}
}
Note : Look below link also I have answered for question similar to this.It will be help full for you
How to Parse an example string in C#
I have done it like:
using (StreamReader sr = File.OpenText(jsonFilePath))
{
var myObject = JsonConvert.DeserializeObject<List<YourObject>>(sr.ReadToEnd());
}
also, you can do this with async call like: sr.ReadToEndAsync().
using Newtonsoft.Json as reference.
Hope, this helps.
See Microsofts JavaScriptSerializer
The JavaScriptSerializer class is used internally by the asynchronous
communication layer to serialize and deserialize the data that is
passed between the browser and the Web server. You cannot access that
instance of the serializer. However, this class exposes a public API.
Therefore, you can use the class when you want to work with JavaScript
Object Notation (JSON) in managed code.
Namespace: System.Web.Script.Serialization
Assembly: System.Web.Extensions (in System.Web.Extensions.dll)

Categories

Resources