It's been a long time, everyone at Qiita. It's been a long time since the last time, but since then I bought a new computer. And I got tired of Python, so I decided to try C #.
Write it down as a memo to understand. Please forgive the gabber points.
I used to use json in Python to store configuration files and data that had to be defined in json for convenience, so I definitely wanted to use it in C # as well. I was a little aware, but I was wondering what a great library Python has.
hoge.json
{
"hoge": "hoge1",
"hogehoge": "hoge2",
"hogehogehoge": "hoge3"
}
Although loading json in Python uses the json library
import json
def load_json(filename):
with open(filename) as files:
load = json.load(files)
return load
If you define one function like this, it will come back as a dictionary type.
result = load_json("hoge.json")
hoge1 = result["hoge"]
hoge2 = result["hogehoge"]
hoge3 = result["hogehogehoge"]
print(hoge1)
print(hoge2)
print(hoge3)
print(type(hoge1))
print(type(hoge2))
print(type(hoge3))
hoge1
hoge2
hoge3
<class 'str'>
<class 'str'>
<class 'str'>
If you do this, you can easily return with str or int, so you can easily use it if you boil or bake it. (Gabber Code Degomen)
For C #
using System;
using System.IO;
using System.Text;
using System.Text.Json;
namespace ConsoleApp2
{
class Program
{
public static string ReadAllLine(string filePath, string encodingName)
{
StreamReader sr = new StreamReader(filePath, Encoding.GetEncoding(encodingName));
string allLine = sr.ReadToEnd();
sr.Close();
return allLine;
}
class hogejson
{
public string hoge { get; set; }
public string hogehoge { get; set; }
public string hogehogehoge { get; set; }
}
static void Main(string[] args)
{
string readjson = ReadAllLine("hoge.json", "utf-8");
hogejson jsonData = JsonSerializer.Deserialize<hogejson>(readjson);
string hoge = jsonData.hoge;
string hogehoge = jsonData.hogehoge;
string hogehogehoge = jsonData.hogehogehoge;
Console.WriteLine(hoge);
Console.WriteLine(hogehoge);
Console.WriteLine(hogehogehoge);
Console.WriteLine(hoge.GetType());
Console.WriteLine(hogehoge.GetType());
Console.WriteLine(hogehogehoge.GetType());
}
}
}
hoge1
hoge2
hoge3
System.String
System.String
System.String
If you do not write it like this, it will not read well, but the most personally troublesome thing is ** "I have to create a json class" ** Noto ** "It's hard to understand when I make a method (a function in Python (although it's a little different))! I got caught.
In Python, the return value returned by the previous function must be ** dictionary type **, while in C #, ** specific return value ** must be specified. For this reason, in Python, it comes back as a dictionary type.
hoge = result["hoge"]
You can retrieve the value "hoge1" of the key "hoge" just by specifying it in and result. On the other hand, C # is set to hoge of class "hogejson" as string type (str) when the value of "hoge" which is the key of "hoge.json" is "hoge1". On the contrary, if you try to set this with an int type or another type, you cannot.
This is because the return value of class hoge is determined to be string. Therefore, since it is not specified as a return value in the dictionary type that was often taken care of in Python, even if the return value is specified as a dictionary type "arbitrarily", not only the keys of other "hogehoge" and "hogehogehoge" but also the value I don't even have the information (self-interpretation)
When I searched for it, it seems that there is a "Dictionary class" in C #, so it can be used in the same way as Python's dictionary type.
Then the story is quick, here is the result of repeated trial and error so that the key and value of hoge.json can be packed in a dictionary type.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
namespace ConsoleApp2
{
class library
{
//File reading
public string ReadAllLine(string filePath, string encodingName)
{
StreamReader sr = new StreamReader(filePath, Encoding.GetEncoding(encodingName));
string allLine = sr.ReadToEnd();
sr.Close();
return allLine;
}
//Forcibly convert List type to Dictionary type
public static Dictionary<string, string> ListInDictionary(string[] left, string[] right)
{
//When they match
if (left.Length == right.Length)
{
var result = new Dictionary<string, string>();
//Turn for by the number of Lists on the left
for (int i = 0; i < left.Length; i++)
{
//Add dictionary to result
result.Add(left[i], right[i]);
}
return result;
}
//When there is a discrepancy
else
{
return null;
}
}
class hogejson
{
public string hoge { get; set; }
public string hogehoge { get; set; }
public string hogehogehoge { get; set; }
}
//hoge.Method to load json
public Dictionary<string, string> GetHogejson(string filename)
{
try
{
string jsonfile = ReadAllLine(filename, "utf-8");
hogejson jsonData = JsonSerializer.Deserialize<hogejson>(jsonfile);
string[] json_key = { "hoge", "hogehoge", "hogehogehoge" };
string[] json_value = { jsonData.hoge, jsonData.hogehoge, jsonData.hogehogehoge };
var result = ListInDictionary(json_key, json_value);
return result;
}
//When json cannot be read
catch (JsonException)
{
return null;
}
}
}
class Program
{
static void Main(string[] args)
{
library Library = new library();
Dictionary<string, string> gethogejson = Library.GetHogejson("hoge.json");
string hoge, hogehoge, hogehogehoge;
hoge = gethogejson["hoge"];
hogehoge = gethogejson["hogehoge"];
hogehogehoge = gethogejson["hogehogehoge"];
Console.WriteLine(hoge);
Console.WriteLine(hogehoge);
Console.WriteLine(hogehogehoge);
Console.WriteLine(hoge.GetType());
Console.WriteLine(hogehoge.GetType());
Console.WriteLine(hogehogehoge.GetType());
}
}
}
... I felt it too aggressively ...
Personally, I'm most grateful that it can be used like Python, but I feel like it's too aggressive and angry.
By the way, the result is
hoge1
hoge2
hoge3
System.String
System.String
System.String
It will be displayed like this.
If you find something like "This is better than this method ~~~ Gabber too much, use this ~~", don't hesitate to comment! I was in serious trouble, so I will try to improve it if I have time.
Postscript What is this? It often comes out and gets stuck. In this case, there is no choice but to save and restart it, which is very inconvenient.
I wrote it down after a long time. good night.
https://usefuledge.com/csharp-json.html https://json2csharp.com/ (The site that creates the json data class based on the json data, which is very convenient) Thank you!!!!!
Recommended Posts