简体   繁体   English

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

[英]C# Trying to split a string to get json object value

I am trying to split a string to get json object value - I have text values with numerous lines in the format: 我正在尝试拆分字符串以获取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"}" },

What I would really like is to get them in the format: 我真正想要的是采用以下格式:

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" },

I know I can use JObject.Parse(data); 我知道我可以使用JObject.Parse(data); to parse the json value - but just tring to get to it is becoming a bit of a nightmare. 解析json值-但是尝试去获取它正变成一场噩梦。 Is there a better way of doing this? 有更好的方法吗?

What I have so far: 到目前为止,我有:

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);
    }

However I am getting a NullReferenceException - even though a string is being passed in to the JsonSplitString method. 但是,我正在收到NullReferenceException即使将字符串传递给JsonSplitString方法。

You are calling reader.Readline() twice: once for the comparison and then again inside your loop. 您两次调用reader.Readline() :一次用于比较,然后再次在循环内。 You are actually skipping every other line. 实际上,您正在跳过其他所有行。 And what is probably happening is that you are reaching the end of your file and then calling reader.Readline() again, which is null. 而且可能发生的情况是,您到达文件的末尾,然后再次调用reader.Readline() ,该参数为null。 Try this instead: 尝试以下方法:

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);
        }
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM