0

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.

Paolo B
  • 3,026
  • 5
  • 21
  • 43
  • The best way to read the json objects is using deserializer. See the answers to this question: http://stackoverflow.com/questions/7895105/deserialize-json-with-c-sharp – Sparrow Feb 04 '17 at 16:44
  • Thanks but I need to be able to get to the string to deserialize it. – Paolo B Feb 04 '17 at 16:48

2 Answers2

1

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();
}
Matt Spinks
  • 6,380
  • 3
  • 28
  • 47
  • I am getting, `CS0029 Cannot implicitly convert type 'string' to 'bool' `error on the `while (line = reader.ReadLine())` line – Paolo B Feb 04 '17 at 16:36
  • My mistake. Yes, that is what you need. I also added an alternative edit in my answer. Sorry, I was getting Javascript and C# mixed up there. – Matt Spinks Feb 04 '17 at 16:42
0
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);
        }
    }
  }
}
coder
  • 8,346
  • 16
  • 39
  • 53