因此,我对编程相当陌生,但我希望更深入地了解它。我最近开始参与一个项目,为一个使用JSON系统的网站创建一个WinForm程序。
我以前从未使用过API,所以我不太确定它是如何工作的,但看了几分钟之后,我似乎掌握了它的要点。我不明白的是,在C#中解析JSON到底是如何工作的。
我在谷歌上搜索了一下,找到了this link 。我用这段代码(在某种程度上)让它工作。
static void Main(string[] args)
{
WebClient c = new WebClient();
var vLogin = c.DownloadString("https://www.openraid.us/index.php/api/login/username/password");
//Returns string
//{"status":1,"error":null,"token":"250-1336515541-c48d354d96e06d488d1a2530071ef07c9532da26"}
//Token = random, no decisive length*/
JObject o = JObject.Parse(vLogin);
Console.WriteLine("Login Status: " + o["status"]);
String sToken = "" + o["token"];
Console.WriteLine(sToken);
Console.WriteLine("");
//Breaks after this
var myRaids = c.DownloadString("https://www.openraid.us/index.php/api/myraids/"+sToken);
JObject r = JObject.Parse(myRaids); //error occurs here
String sEventId = "" + r["event_id"];
Console.WriteLine("Event ID: " + sEventId);
Console.ReadLine();
}
所以对我来说,看起来我已经完成了对1个页面的解析和处理,但是当我转到第二个页面时,我得到了这个错误。
从JsonReader读取JObject时出错。当前JsonReader项不是对象: StartArray。路径'',行% 1,位置% 1。
因此,我想我的问题是,如何解析多个页面或调用JSON,以及将JSON对象的每个部分(如status
、error
和token
)分解为C#字符串的最简单方法是什么?
发布于 2012-06-28 19:56:22
你有没有尝试过使用JArray?这取决于您尝试返回的对象的类型
WebClient client = new WebClient();
var data = client.DownloadString("");
var jArray = JArray.Parse(data);
发布于 2012-05-09 09:54:32
JSON要求在多个对象之间使用方括号表示数组和逗号。
这是per the JSON standard。我还建议使用JSON.net via NuGet而不是原生JSON解析器,除非它过于夸张,您不能有额外的膨胀。
例如,您解析包含两个独立JSON对象的文件-以下内容不符合JSON标准(两个对象之间缺少逗号,并且两个对象没有用括号封装):
{"status":1,"error":null}
{"status":2,"error":null}
从文件中解析的以下3个JSON对象确实有效(多个对象使用方括号,对象之间使用逗号):
[{"glossary": {"title": "fun glossary","SeeAlso": ["GML", "XML"]},
{"glossary": {"title": "grey glossary","SeeAlso": ["GML", "XML"]},
{"glossary": {"title": "blue glossary","SeeAlso": ["GML", "XML"]}]
发布于 2012-05-09 06:29:20
您可以使用for循环将每个C#对象(数组)分割成更多的对象
var jsonArray = JsonArray.Parse(st);//st is the string which contain the JSON objects
foreach (var item in jsonArray) {
JsonObject ob = new JsonObject(item);
foreach (var t in ob.Values) {
JsonObject oo = new JsonObject(t);
foreach (var x in oo) {
textBox1.AppendText(x.Key + “ : ” + x.Value + “\n”);
}
}
}
https://stackoverflow.com/questions/10507416
复制相似问题