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?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
dubyaa
  • 199
  • 1
  • 7
  • 17
  • 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. – Flater Feb 27 '13 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](http://stackoverflow.com/questions/11345382/convert-object-to-json-string-in-c-sharp). – SWalters Feb 27 '13 at 16:05
  • Sandra, I used the Newtonsoft library, thanks. – dubyaa Feb 27 '13 at 23:04

2 Answers2

4

Here's how you would do it:

JsonObject character = new JsonObject();
character.Add("Name",JsonValue.CreateStringValue("Alex"));
W.K.S
  • 9,787
  • 15
  • 75
  • 122
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.

JP Alioto
  • 44,864
  • 6
  • 88
  • 112
  • 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: http://stackoverflow.com/questions/10965829/how-do-i-de-serialize-json-in-winrt – Jerry Nixon Jun 30 '14 at 22:48