简体   繁体   中英

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:

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); to parse the json value - but just tring to get to it is becoming a bit of a nightmare. 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.

You are calling reader.Readline() twice: once for the comparison and then again inside your loop. 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. 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);
        }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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