简体   繁体   中英

Parsing JSON Name Pair in C#

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?

Use Newtonsoft JSON :

JObject jsonObject = JObject.Parse(json);
foreach(var jsonItem in jsonObject)
{
    Console.WriteLine(jsonItem.Key);
}
Console.ReadKey();

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.

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);    
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM