programing

C #에서 Json 파일 읽기 및 구문 분석

new-time 2020. 5. 9. 17:13
반응형

C #에서 Json 파일 읽기 및 구문 분석


나는 이틀 동안 코드 샘플 등을 다루면서 "faffing"의 가장 큰 부분을 보냈다. 매우 큰 JSON 파일을 c #의 배열로 읽으려고 노력했다. 그래서 나중에 처리를 위해 2d 배열로 나눌 수있다.내가 겪고있는 문제는 내가하려는 일을하는 사람들의 예를 찾을 수 없다는 것입니다. 이것은 내가 최선을 다하기 위해 코드를 약간 편집하고 있음을 의미했습니다.나는 다음과 같은 일을 할 수 있었다.

  • 파일을 읽습니다. 헤더를 누락하고 값을 배열로 읽습니다.
  • 배열의 각 행에 일정량의 값을 배치하십시오. (그래서 나중에 2D 배열로 풋을 나눌 수 있습니다)

이것은 아래 코드로 수행되었지만 배열에 몇 줄을 입력하면 프로그램이 충돌합니다. 파일 크기와 관련이있을 수 있습니다.

// If the file extension was a jave file the following 
// load method will be use else it will move on to the 
// next else if statement
if (fileExtension == ".json") 
{
    int count = 0;
    int count2 = 0;
    int inOrOut = 0;
    int nRecords=1; 
    JsonTextReader reader = new JsonTextReader(new StreamReader(txtLoaction.Text));
    string[] rawData = new string[5];
    while (reader.Read())
    {
        if (reader.Value != null)
            if (inOrOut == 1)
            {
                if (count == 6)
                {
                    nRecords++;
                    Array.Resize(ref rawData, nRecords);
                    //textBox1.Text += "\r\n";
                    count = 0;
                }
                rawData[count2] += reader.Value + ","; //+"\r\n"
                inOrOut = 0;
                count++;
                if (count2 == 500)
                {
                    MessageBox.Show(rawData[499]);
                }
            }
            else
            {
                inOrOut = 1;
            }
    } 
}

내가 작업하고있는 JSON의 스 니펫은 다음과 같습니다.

[ 
    { "millis": "1000", 
      "stamp": "1273010254", 
      "datetime": "2010/5/4 21:57:34", 
      "light": "333", 
      "temp": "78.32", 
      "vcc": "3.54" }, 
] 

I need the values out of this JSON. For example, I need "3.54", but I would not want it to print the "vcc".

I am hoping someone can show me how to read a JSON file in and only extract the data that I need and put it into an array or something that I can use to later put into an array.


How about making all the things easier with Json.NET?

public void LoadJson()
{
    using (StreamReader r = new StreamReader("file.json"))
    {
        string json = r.ReadToEnd();
        List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
    }
}

public class Item
{
    public int millis;
    public string stamp;
    public DateTime datetime;
    public string light;
    public float temp;
    public float vcc;
}

You can even get the values dynamically without declaring Item class.

dynamic array = JsonConvert.DeserializeObject(json);
foreach(var item in array)
{
    Console.WriteLine("{0} {1}", item.temp, item.vcc);
}

Doing this yourself is an awful idea. Use Json.NET. It has already solved the problem better than most programmers could if they were given months on end to work on it. As for your specific needs, parsing into arrays and such, check the documentation, particularly on JsonTextReader. Basically, Json.NET handles JSON arrays natively and will parse them into strings, ints, or whatever the type happens to be without prompting from you. Here is a direct link to the basic code usages for both the reader and the writer, so you can have that open in a spare window while you're learning to work with this.

This is for the best: Be lazy this time and use a library so you solve this common problem forever.


Based on @L.B.'s solution, the (typed as Object rather than Anonymous) VB code is

Dim oJson as Object = JsonConvert.DeserializeObject(File.ReadAllText(MyFilePath))

I should mention that this is quick and useful for constructing HTTP call content where the type isn't required. And using Object rather than Anonymous means you can maintain Option Strict On in your Visual Studio environment - I hate turning that off.


string jsonFilePath = @"C:\MyFolder\myFile.json";

        string json = File.ReadAllText(jsonFilePath);
        Dictionary<string, object> json_Dictionary = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(json);

        foreach (var item in json_Dictionary)
        {
            // parse here
        }

For finding the right path I'm using

   var pathToJson = Path.Combine("my","path","config","default.Business.Area.json");
   var r = new StreamReader(pathToJson);
   var myJson = r.ReadToEnd();

   // my/path/config/default.Business.Area.json 
   [...] do parsing here 

Path.Combine uses the Path.PathSeparator and it checks whether the first path has already a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.

See https://stackoverflow.com/a/32071002/4420355

참고URL : https://stackoverflow.com/questions/13297563/read-and-parse-a-json-file-in-c-sharp

반응형