0

Using C# to parse JSON URL I am facing some issues. As you know JSON data is written as name/value pairs. now in URL JSON I have these data:

{  
   "currentVersion":10.41,
   "serviceDescription":"There are some text here",
   "hasVersionedData":true,
   "supportsDisconnectedEditing":false,
   "syncEnabled":false,
   "supportedQueryFormats":"JSON",
   "maxRecordCount":1000
 }

and I want to only print out the name part of the JSON data using this code

using (var wc = new WebClient())
{
    string json = wc.DownloadString("http://xxxxxxxxx?f=pjson");
    try
    {
        dynamic data = Json.Decode(json);
        for (int i = 0; i <= data.Length - 1; i++)
        {
            Console.WriteLine(data[0]);
        }

    }
    catch (Exception e)
    {

    }
}

but this is not printing any thing on the console! can you please let me know what I am doing wrong?

Behseini
  • 6,066
  • 23
  • 78
  • 125

3 Answers3

2

Use Newtonsoft JSON:

JObject jsonObject = JObject.Parse(json);
foreach(var jsonItem in jsonObject)
{
    Console.WriteLine(jsonItem.Key);
}
Console.ReadKey();
Renats Stozkovs
  • 2,549
  • 10
  • 22
  • 26
0

Create an object to hold the results

public class RootObject
{
    public double currentVersion { get; set; }
    public string serviceDescription { get; set; }
    public bool hasVersionedData { get; set; }
    public bool supportsDisconnectedEditing { get; set; }
    public bool syncEnabled { get; set; }
    public string supportedQueryFormats { get; set; }
    public int maxRecordCount { get; set; }
}

Use a JavaScriptSerializer to deserialize the result.

var serializer = new JavaScriptSerializer();
var rootObject= serializer.Deserialize<RootObject>(json);

Console.WriteLine(rootObject.currentVersion);
Console.WriteLine(rootObject.serviceDescription);
etc.
Tarzan
  • 4,270
  • 8
  • 50
  • 70
0

If you are running this under Debug, see here: Attempt by method 'System.Web.Helpers.Json..cctor()' to access method 'System.Web.Helpers.Json.CreateSerializer()' failed once I unchecked Enable the Visual Studio hosting process it run with results. However, to get what I think you want (a listing of each of the key/value pairs I switched to a foreach and it printed it out nicely:

try   

    {    
        var data = Json.Decode(jsonData);    
        //for (var i = 0; i <= data.Length - 1; i++)    
        foreach (var j in data)    
        {    
            Console.WriteLine(j);    
        }    
    }    
    catch (Exception e)    
    {    
        Console.WriteLine(e);    
    }
Community
  • 1
  • 1