C# 尝试拆分字符串以获得 json 对象值

C# Trying to split a string to get json object value

我正在尝试拆分字符串以获得 json 对象值 - 我的文本值包含许多行,格式如下:

new Car() { Id = 1, Year = 1926, Make = "Chrysler", Model = "Imperial", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRPe4CygIW-MuZL5jl77wlgXXK5_ANyC9l1X4QqLizCOkaVAlRe","image_url":"http://imperialclub.org/Yr/1926/photos/Phaeton2Big.jpg","width":1632,"height":1032}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
new Car() { Id = 2, Year = 1950, Make = "Hillman", Model = "Minx Magnificent", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcScVsGEeRBh6xZYXr6Gm35Sk5ecSlk_ax3qZmoGRAtBbZC8vJZ9","image_url":"http://i.ebayimg.com/images/g/gcIAAOSwKadXPeLs/s-l300.jpg","width":300,"height":225}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
new Car() { Id = 3, Year = 1954, Make = "Chevrolet", Model = "Corvette", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSdZntu4tgWrZrxwqeuKlteCP9vJGnqUlmNq5JF1bBCf-EJy5r8","image_url":"http://momentcar.com/images/chevrolet-corvette-1954-1.jpg","width":1000,"height":600}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },

我真正想要的是以格式获取它们:

new Car() { Id = 1, Year = 1926, Make = "Chrysler", Model = "Imperial", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRPe4CygIW-MuZL5jl77wlgXXK5_ANyC9l1X4QqLizCOkaVAlRe" },
new Car() { Id = 2, Year = 1950, Make = "Hillman", Model = "Minx Magnificent", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcScVsGEeRBh6xZYXr6Gm35Sk5ecSlk_ax3qZmoGRAtBbZC8vJZ9" },
new Car() { Id = 3, Year = 1954, Make = "Chevrolet", Model = "Corvette", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSdZntu4tgWrZrxwqeuKlteCP9vJGnqUlmNq5JF1bBCf-EJy5r8" },

我知道我可以使用 JObject.Parse(data); 来解析 json 值 - 但只是试图得到它有点像一场噩梦。有更好的方法吗?

我目前拥有的:

static void Main(string[] args)
    {

        using (StreamWriter writer = new StreamWriter(@"c:\Data\temp\output.txt")) // file to write to
        {
            using (StreamReader reader = new StreamReader(@"c:\Data\temp\test.txt")) //file to read from
            {
                string line;

                while (reader.ReadLine() != null)
                {
                    line = reader.ReadLine();

                    string[] words = JsonSplitString(line);

                    string json = words[1];

                    writer.WriteLine("{0}", json);
                }
            }
        }

    }

    static string[] JsonSplitString(string data)
    {
        return data.Split(new string[] { "ImageUrl" }, StringSplitOptions.None);
    }

但是我得到了一个 NullReferenceException - 即使一个字符串被传递到 JsonSplitString 方法。

您正在调用 reader.Readline() 两次:一次用于比较,然后在循环内再次调用。你实际上是在跳过每一行。可能发生的情况是您到达文件末尾,然后再次调用 reader.Readline(),这是空的。试试这个:

line = reader.ReadLine();
while (line != null)
{
    string[] words = JsonSplitString(line);
    string json = words[1];
    writer.WriteLine("{0}", json);
    line = reader.ReadLine();
}
using System;
using Newtonsoft.Json.Linq;

namespace JsonExperiments
{
    class Program
    {
        static void Main(string[] args)
        {
            ExecuteEmployeeSearch();
            Console.ReadLine();
        }

    static void ExecuteEmployeeSearch()
    {
        // mockup JSON that would be returned from API
        string sampleJson = "{\"results\":[" +
            "{\"employeename\":\"name1\",\"employeesupervisor\":\"supervisor1\"}," +
            "{\"employeename\":\"name2\",\"employeesupervisor\":\"supervisor1\"}," +
            "{\"employeename\":\"name3\",\"employeesupervisor\":[\"supervisor1\",\"supervisor2\"]}" +
            "]}";

        // Parse JSON into dynamic object, convenient!
        JObject results = JObject.Parse(sampleJson);

        // Process each employee
        foreach (var result in results["results"])
        {
            // this can be a string or null
            string employeeName = (string)result["employeename"];

            // this can be a string or array, how can we tell which it is
            JToken supervisor = result["employeesupervisor"];

            string supervisorName = "";
            if (supervisor is JValue)
            {
                supervisorName = (string)supervisor;
            }
            else if (supervisor is JArray)
            {
                // can pick one, or flatten array to a string
                supervisorName = (string)((JArray)supervisor).First;
            }

            Console.WriteLine("Employee: {0}, Supervisor: {1}", employeeName, supervisorName);
        }
    }
  }
}