.

json and xml to c#

http://json2csharp.com/#

http://jsonutils.com/

 

using System.Json for dynamic json

open your package manager console and type:

Install-Package System.Json -Version 4.0.20126.16343

add the reference to your code:

using System.Json;

and finally example usage:

var json = GetJson(input);
dynamic result = JsonValue.Parse(json);

Custom Json

This is how you can write out your own custom Json code in MVC:

public ActionResult hello()
{
    dynamic d = new JObject();
    d.MetricId = 11;
    string json = Newtonsoft.Json.JsonConvert.SerializeObject(d);
    return Content(json,"JSon");
}

AllowGet JsonRequestBehavior

Getting the following error:
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

Try to add “JsonRequestBehavior.AllowGet” to your return statement.

public JsonResult GetJsonData()
{
    MetricValue m = new MetricValue();
    m.Error = "234";
    m.SnapshotId = 4;
    return Json(m, JsonRequestBehavior.AllowGet);
}

now my output is:

{"MetricId":0,"SnapshotId":4,"Error":"234","Value":null}

 

Loading a web page using json data

sdf

function UpdateOnClick(param123) {
    $.ajax({
        type: 'GET',
        url: "/WhereEver/PageToLoad",
        cache: false,
        data: { myKey: myValue },
        dataType: "json",
        async: true,
        success: function (result) {
            $('#Id1').html(result.ValueX);
            $('#Id2').html(result.ValueY);
        },
        error: function (result) {

        }
    });
}

Convert Json To Xml

code

var jsonOutput = @"{""Feeds"":[{""InstrumentName"":""Natural Gas"",""DailyHigh"":3.497,""DailyLow"":3.439,""Change"":0.15882183078255849,""InstrumentID"":123,""BuyRate"":3.471,""SellRate"":3.466},{""InstrumentName"":""Heating Oil"",""DailyHigh"":3.0944,""DailyLow"":3.0436,""Change"":0.70009768804949535,""InstrumentID"":430,""BuyRate"":3.0935,""SellRate"":3.0915}],""Type"":11}";
var myelement = JsonConvert.DeserializeXmlNode(jsonOutput, "ThisGetsIgnored").FirstChild; //Newtonsoft.Json.JsonConvert
var xml = myelement.InnerXml;
Console.WriteLine(xml);

input

{
   "Feeds":[
      {
         "InstrumentName":"Natural Gas",
         "DailyHigh":3.497,
         "DailyLow":3.439,
         "Change":0.15882183078255849,
         "InstrumentID":123,
         "BuyRate":3.471,
         "SellRate":3.466
      },
      {
         "InstrumentName":"Heating Oil",
         "DailyHigh":3.0944,
         "DailyLow":3.0436,
         "Change":0.70009768804949535,
         "InstrumentID":430,
         "BuyRate":3.0935,
         "SellRate":3.0915
      }
   ],
   "Type":11
}

output

<Feeds>
  <InstrumentName>Natural Gas</InstrumentName>
  <DailyHigh>3.497</DailyHigh>
  <DailyLow>3.439</DailyLow>
  <Change>0.15882183078255849</Change>
  <InstrumentID>123</InstrumentID>
  <BuyRate>3.471</BuyRate>
  <SellRate>3.466</SellRate>
</Feeds>
<Feeds>
  <InstrumentName>Heating Oil</InstrumentName>
  <DailyHigh>3.0944</DailyHigh>
  <DailyLow>3.0436</DailyLow>
  <Change>0.70009768804949535</Change>
  <InstrumentID>430</InstrumentID>
  <BuyRate>3.0935</BuyRate>
  <SellRate>3.0915</SellRate>
</Feeds>
<Type>11</Type>

Deserializing Json

[TestMethod]
public void Deserialize_Concrete()
{
    string json =
        @"[{""Feeds"":[{""InstrumentName"":""Natural Gas"",""DailyHigh"":3.497,""DailyLow"":3.439,""Change"":0.15882183078255849,""InstrumentID"":123,""BuyRate"":3.471,""SellRate"":3.466},{""InstrumentName"":""Heating Oil"",""DailyHigh"":3.0944,""DailyLow"":3.0436,""Change"":0.70009768804949535,""InstrumentID"":430,""BuyRate"":3.0935,""SellRate"":3.0915}],""Type"":11}]";
    var serializer = new JavaScriptSerializer();
    var qwer = serializer.Deserialize<List<FeedbackReport>>(json);
}

[Serializable]
public class FeedbackReport
{
    public List<Feed> Feeds;
}

[Serializable]
public class Feed
{
    public float BuyRate;
    public float Change;
    public float DailyHigh;
    public float DailyLow;
    public string InstrumentID;
    public string InstrumentName;
    public float SellRate;
}

[TestMethod]
public void Deserialize_Dynamically()
{
    string json =
        @"[{""Feeds"":[{""InstrumentName"":""Natural Gas"",""DailyHigh"":3.497,""DailyLow"":3.439,""Change"":0.15882183078255849,""InstrumentID"":123,""BuyRate"":3.471,""SellRate"":3.466},{""InstrumentName"":""Heating Oil"",""DailyHigh"":3.0944,""DailyLow"":3.0436,""Change"":0.70009768804949535,""InstrumentID"":430,""BuyRate"":3.0935,""SellRate"":3.0915}],""Type"":11}]";

    var serializer = new JavaScriptSerializer();  //System.Web.Script.Serialization.JavaScriptSerializer

    //might perhaps need the following line - not always
    //serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

    var DeserializedObj = serializer.Deserialize(json, typeof(object));
}

Json.Decode

<code>Ensure your project "<code>properties</code>" is set to
".NET Framework 4"  (not the Client Profile version)</code>

Add a “.Net” reference:
System.Web.Helpers (2.0.0.0) (v4.0.30319)

include your reference:

using System.Web.Helpers;

 

and deserialize:

var dynamicObject = Json.Decode(jsonString);

alternatively, without dynamics, just a dictionary:

var deserializedString = new JavaScriptSerializer().Deserialize<Dictionary<string, Dictionary<string, int>>>(val);
var myVals = deserializedString["mainkey"];

and getting results:

foreach (string key in myVals.Keys)
    Console.WriteLine(key + ": " + myVals[key]);

or use json.net

IE7 specific styles

      &lt;!--[if IE 7]&gt;
            &lt;script src="@Url.Content("~/Scripts/json2.js")" type="text/javascript"&gt;&lt;/script&gt;
      &lt;![endif]--&gt;

<a href="http://blog.bitlinkit.com/wp-content/uploads/2013/04/json2.js">json2</a>

JSON serialization

//This is just used to serialize the results to the file as JSON and read it back
private static string ToJson(T obj)
{
MemoryStream stream = new MemoryStream();

try
{
DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof (T));
jsSerializer.WriteObject(stream, obj);

return Encoding.UTF8.GetString(stream.ToArray());
}
finally
{
stream.Close();
stream.Dispose();
}
}

private static T FromJson(string input)
{
MemoryStream stream = new MemoryStream();

try
{
DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof (T));
stream = new MemoryStream(Encoding.UTF8.GetBytes(input));
T obj = (T) jsSerializer.ReadObject(stream);

return obj;
}
finally
{
stream.Close();
stream.Dispose();
}
}