0

I am creating a Windows 8 App in C# using Visual Studio. I am trying to take a bunch of data input and create a JSON object from that data. Here is my preliminary test method that does not work:

        IJsonValue name = "Alex"; 
        JsonObject Character = new JsonObject();
        Character.Add("Name", name);

The error that I am getting is

Cannot Implicitly convert type 'string' to 'Windows.Data.Json.IJsonValue'

I looked up the documentation for IJsonValue but couldn't figure out how to create an instance of IJsonValue containing a string. So how do I store data in an IJsonValue to be added to a JsonObject?

3
  • 2
    IJsonValue is an interface, not a class (hence the "I" as prefix). The only thing you can assign to IJsonValue name is an object whose class implements the IJsonValue interface. Commented Feb 27, 2013 at 15:32
  • 1
    If your data is in a class, probably the easiest way to convert it to JSON would be to use the Newtonsoft JSON.NET library and call SerializeObject with your class instance... example here. Commented Feb 27, 2013 at 16:05
  • Sandra, I used the Newtonsoft library, thanks. Commented Feb 27, 2013 at 23:04

2 Answers 2

4

Here's how you would do it:

JsonObject character = new JsonObject();
character.Add("Name",JsonValue.CreateStringValue("Alex"));
Sign up to request clarification or add additional context in comments.

Comments

3

The class JsonValue implements the IJsonValue interface. You can create an instance of the class and use it like this for example ...

JsonValue jsonValue = JsonValue.Parse("{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"IDs\": [116, 943, 234, 38793]}");
double width = jsonValue.GetObject().GetNamedNumber("Width");
double height = jsonValue.GetObject().GetNamedNumber("Height");
string title = jsonValue.GetObject().GetNamedString("Title");
JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");

Check out this for more examples.

1 Comment

It's worth pointing out that handling JSON in this manner (almost like xpath) is a little brittle because there is little opportunity for typing and compile-time checks. Deserializing JSON into a strongly typed class is a more long-term and reliable approach that also gives you easier interaction with the data. It doesn't mean this GetNamedString approach does not work, it does. It's just a more typed and controlled approach that easier to use and less likely to break. :) Here's some info on it: stackoverflow.com/questions/10965829/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.