JSON Library for C#

JSON library for C#

JSON.Net

Easy to use strongly-typed JSON library for C#

http://james.newtonking.com/projects/json-net.aspx is the usual answer but there are many more.

        List<string> names = new List<string>() {"Mike","Joe","Jane"};
Dictionary<string, int> ids = new Dictionary<string, int>()
{
{"Mike",1},
{"Joe",2},
{"Jane",3},
};

// ["Mike","Joe","Jane"]
string nameJson = Newtonsoft.Json.JsonConvert.SerializeObject(names);

//{"Mike":1,"Joe":2,"Jane":3}
string idsJSon = Newtonsoft.Json.JsonConvert.SerializeObject(ids);

How to parse JSON without JSON.NET library?

You can use the classes found in the System.Json Namespace which were added in .NET 4.5. You need to add a reference to the System.Runtime.Serialization assembly

The JsonValue.Parse() Method parses JSON text and returns a JsonValue:

JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ...");

If you pass a string with a JSON object, you should be able to cast the value to a JsonObject:

using System.Json;

JsonObject result = value as JsonObject;

Console.WriteLine("Name .... {0}", (string)result["name"]);
Console.WriteLine("Artist .. {0}", (string)result["artist"]);
Console.WriteLine("Genre ... {0}", (string)result["genre"]);
Console.WriteLine("Album ... {0}", (string)result["album"]);

The classes are quite similar to those found in the System.Xml.Linq Namespace.

C# library for converting json schema to sample JSON

Ok, it is super simplistic and doesn't take into account many factors of JSON schema, but it might be a good enough starting point for you. It also depends on the JsonSchema library from Newtonsoft.

   public class JsonSchemaSampleGenerator
{
public JsonSchemaSampleGenerator()
{
}

public static JToken Generate(JsonSchema schema)
{
JToken output;
switch (schema.Type)
{
case JsonSchemaType.Object:
var jObject = new JObject();
if (schema.Properties != null)
{
foreach (var prop in schema.Properties)
{
jObject.Add(TranslateNameToJson(prop.Key), Generate(prop.Value));
}
}
output = jObject;
break;
case JsonSchemaType.Array:
var jArray = new JArray();
foreach (var item in schema.Items)
{
jArray.Add(Generate(item));
}
output = jArray;
break;

case JsonSchemaType.String:
output = new JValue("sample");
break;
case JsonSchemaType.Float:
output = new JValue(1.0);
break;
case JsonSchemaType.Integer:
output = new JValue(1);
break;
case JsonSchemaType.Boolean:
output = new JValue(false);
break;
case JsonSchemaType.Null:
output = JValue.CreateNull();
break;

default:
output = null;
break;

}

return output;
}

public static string TranslateNameToJson(string name)
{
return name.Substring(0, 1).ToLower() + name.Substring(1);
}
}


Related Topics



Leave a reply



Submit