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}");
}
}
Related
YamlDotNet can deserialize a yaml document which contain json.
Suppose there is a yaml document as input like below.
fieldA: a
fieldB:
- { "subFieldA": "a1","subFieldB": "b1" }
- { "subFieldA": "a2","subFieldB": "b2" }
Then, I deserialize it and re-serialize.
class Program
{
static void Main(string[] args)
{
using var sr = new StreamReader("test.yaml");
var deserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.Build();
var output = deserializer.Deserialize<Temp>(sr);
var serializer = new SerializerBuilder()
.Build();
Console.WriteLine(serializer.Serialize(output));
}
}
public class Temp
{
public string FieldA { get; set; }
public List<Dictionary<string, string>> FieldB { get; set; }
}
I would get output like below.
FieldA: a
FieldB:
- subFieldA: a1
subFieldB: b1
- subFieldA: a2
subFieldB: b2
But I want the property FieldB still be serialized to json.
In other words, I want to get a output same as input.
Is there a way to use YamlDotNet to achieve this effect, please?
YamlDotNet is only used for serializing and deserializing YAML. Use the .NET serialization library if all you want to do is actually serialize that dictionary. Obviously the string property cannot do anything with unless it's part of the dictionary.
using System.Text.Json;
var temp = new Temp();
temp.Dict = new Dictionary<string, string>();
temp.Dict.Add("hello", "world");
string json = JsonSerializer.Serialize(temp.Dict);
If you're asking if you can put JSON into YAML, sure, just turn it into a json string first, and add that string as a property of a separate class to serialize into YAML. I don't believe there's a way to automatically get a YAML library to be serializing portions of its stuff into JSON. You can't mix and match.
So I have a JSON string where I just want to read a specific value. How do I just pick "Read me please!" from string below?
var readString = /*Read me please!*/
JSON string:
"{\"aString\":\"Read me please!\"}"
For better understanding, how do I do the same here? (just "Read me please!"):
"{\"Result\":
{
\"aString\":\"Read me please!\",
\"anotherString\":\"Dont read me!\"
}
}"
If both alternative have different solution I would like to know both.
PS: I do not wish to save the value into object/class or so. Just temporary inside var readString.
You could write a model:
public class MyModel
{
public string AString { get; set; }
}
and then use a JSON serializer such as Json.NET:
string readString = "{\"aString\":\"Read me please!\"}";
MyModel model = JsonConvert.DeserializeObject<MyModel>(readString);
Console.WriteLine(model.AString);
If you don't want to use third party solutions you could use the built-in JavaScriptSerializer class:
string readString = "{\"aString\":\"Read me please!\"}";
MyModel model = new JavaScriptSerializer().Deserialize<MyModel>(readString);
Console.WriteLine(model.AString);
Now assuming you want to handle your second JSON string you could simply adapt your model:
public class Wrapper
{
public MyModel Result { get; set; }
}
public class MyModel
{
public string AString { get; set; }
public string AnotherString { get; set; }
}
and then deserialize to this wrapper class:
string readString = ... the JSON string in your second example ...;
Wrapper wrapper = JsonConvert.DeserializeObject<Wrapper>(readString);
Console.WriteLine(wrapper.Result.AString);
Console.WriteLine(wrapper.Result.AnotherString);
UPDATE:
And if you don't want to deserialize to a model you could directly do this:
string readString = "{\"aString\":\"Read me please!\"}";
var res = (JObject)JsonConvert.DeserializeObject(readString);
Console.WriteLine(res.Value<string>("aString"));
or with the built-in JavaScriptSerializer class:
string readString = "{\"aString\":\"Read me please!\"}";
var serializer = new JavaScriptSerializer();
var res = (IDictionary<string, object>)serializer.DeserializeObject(readString);
Console.WriteLine(res["aString"]);
var readString = JObject.Parse(str)["aString"];
Or for your second example:
var readString2 = JObject.Parse(str2)["Result"]["aString"];
Json.NET also provides a JSON reader if you don't want to deserialize the whole thing. For example:
string json = "{\"Result\": { \"aString\":\"Read me please!\", \"anotherString\":\"Dont read me!\" } }";
using (var reader = new JsonTextReader(new StringReader(json)))
{
while (reader.Read())
{
if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "aString")
{
reader.Read();
Console.Write(reader.Value);
break;
}
}
}
Console.ReadKey();
You have to use Newtonsoft (JSON.NET) to accomplish that. Then, you can access your json property this way:
var obj = JsonConvert.DeserializeObject(yourJson);
Console.WriteLine(obj.Result.aString);
I played around with writing a generic method that can read any part of my json string. I tried a lot of the answers on this thread and it did not suit my need. So this is what I came up with. I use the following method in my service layer to read my configuration properties from the json string.
public T getValue<T>(string json,string jsonPropertyName)
{
var parsedResult= JObject.Parse(json);
return parsedResult.SelectToken(jsonPropertyName).ToObject<T>();
}
and this is how you would use it :
var result = service.getValue<List<string>>(json, "propertyName");
So you can use this to get specific properties within your json string and cast it to whatever you need it to be.
I want to write a PowerShell function in C#. During the process I receive a string with JSON content.
My sample json content is:
string json = "{'TestNr':{'Name':'CSHARP', 'Description':'Test Descriptiopn'}}"
This string should be converted to a PSObject just like ConvertFrom-Json would do.
I was trying to create an object with below lines. It works but it would require a lot of manual scripting especially if the JSON string becomes longer.
PSObject obj = new PSObject();
obj.Properties.Add(new PSNoteProperty("Head", "Children"));
I tried also the below line:
obj = (PSObject)TypeDescriptor.GetConverter(typeof(PSObject)).ConvertFromString(json);
For this I get however the error (I run the function in PowerShell 7):
TypeConverter cannot convert from System.String.
There are two ways you can parse the string in C# that would be the easiest to go with.
public class MyClass
{
public TestNRClass TestNR { get; set; }
}
public class TestNRClass
{
public string Name { get; set; }
public string Description { get; set; }
}
// In the main,
string json = #"{""TestNr"":{""Name"":""CSHARP"", ""Description"":""Test Descriptiopn""}}";
MyClass jobj = JsonConvert.DeserializeObject<MyClass>(json);
Console.WriteLine(jobj.TestNR.Name);
This is with the strong typed class object. This is what you should be using in C#.
Other way is to get an object
string json = #"{""TestNr"":{""Name"":""CSHARP"", ""Description"":""Test Descriptiopn""}}";
JObject obj = JObject.Parse(json);
Console.WriteLine(obj.ToString());
Console.WriteLine(obj["TestNr"]["Name"].ToString());
// You can also add more keyValuePair
obj["NewVariable"] = "stest";
Console.WriteLine(obj.ToString()); // Shows the new item as well.
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");
I am taking an HttpRequest and reading it to a string
var body = request.Content.ReadAsStringAsync().Result;
This body gives me a string that looks like the following:
"To=Jim&From=Dan+Bailey"
I want to serialize body to aumatically bind to an object that looks like
public class Letter
{
[JsonProperty("To")]
public string To { get; set; }
[JsonProperty("From")]
public string From { get; set; }
}
Any ideas? I tried using JsonSerializer and Newtonsoft.Json.Convert but both require a different format
Json deserializers would only work on Json strings
You may convert the querystring to a NameValueCollection directly using the utility ParseQueryString
var body = request.Content.ReadAsStringAsync().Result;
var parameters = HttpUtility.ParseQueryString(body);
For most purposes, using a NameValueCollection should suffice, but if you still need a strongly-typed object, I would suggest using either reflection, or first serialize to a json string then use Newtonsoft deserializer
var dict = new Dictionary<string, string>();
foreach (var key in parameters.Keys)
{
dict.Add(key, parameters[key]);
}
var json = JsonConvert.SerializeObject(dict);
var obj = JsonConvert.DeserializeObject<Letter>(json);
What you have is not a JSON but most likely a simple html parameter string. Looks like the format is fixed given how your class Letter looks like.
I guess you can just do it with Regex :
var match = Regex.Match("To=Jim&From=Dan+Bailey", "To=(?<To>[^&]+)&From=(?<From>[^&]+)");
var letter = new Letter() { To = match.Groups["To"].Value, From = match.Groups["From"].Value };