2

What is the best way to create a C# class that can be serialized to as:

marks:          [
             { c: [57.162499, 65.54718], // latitude, longitude - this type of coordinates works only for World Map
               tooltip: 'Tyumen - Click to go to http://yahoo.com', // text for tooltip
               attrs: {
                        href: 'http://yahoo.com',            // link
                        src:  '/markers/pin1_red.png'        // image for marker
                       }
             },
             { xy: [50, 120], // x-y coodinates - works for all maps, including World Map
               tooltip: 'This is London! Click to go to http://london.com',
               attrs: {
                        href: 'http://yahoo.com',            // link
                        src:  '/markers/pin1_yellow.png'     // image for marker
                       }
             }
            ]

In above code we assign either assign 'c' or 'xy' but not both at the same time. I'm using Newtonsoft.Json. The only thing I want is a C# class that can be serialized to above code.

2
  • Do you want a class with two properties or two classes? Commented Aug 16, 2012 at 13:03
  • @WouterdeKort: actually a class 4 properties {c,xy, tooltip,attrs}. Commented Aug 16, 2012 at 13:27

1 Answer 1

4

The class looks like this:

[Serializable]
public class Marks
{
    public List<latlon> marks = new List<latlon>();
}

public class latlon
{
    public double[] c;
    public int[] xy;
    public string tooltip;
    public attributes attrs;

    public latlon (double lat, double lon)
    {
        c = new double[] { lat, lon };
    }
    public latlon (int x, int y)
    {
        xy = new int[] { x, y };
    }
}

public class attributes
{
    public string href;
    public string src;
}

The code to test it looks like this:

string json;

Marks obj = new Marks();
latlon mark = new latlon(57.162, 65.547)
    {
        tooltip = "Tyumen - Click to go to http://yahoo.com",
        attrs = new attributes()
        {
            href = "http://yahoo.com",
            src = "/markers/pin1_red.png"
        }
    };

obj.marks.Add(mark);

mark = new latlon(50, 120)
    {
        tooltip = "This is London! Click to go to http://london.com",
        attrs = new attributes()
        {
            href = "http://yahoo.com",
            src = "/markers/pin1_yellow.png"
        }
    };

obj.marks.Add(mark);

//serialize to JSON, ignoring null elements
json = JsonConvert.SerializeObject(obj, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.