简体   繁体   English

使用C#JSON.NET将Javascript JSON.stringfy字符串转换为对象

[英]Converting a Javascript JSON.stringfy string to an object using c# JSON.NET

I am developing a windows 8 app, and i have some javascript that stores a serialized object into roaming settings, ie: 我正在开发Windows 8应用程序,并且我有一些JavaScript将序列化的对象存储到漫游设置中,即:

var object = [{"id":1}, {"id":2}]
roamingSettings.values["example"] = JSON.stringify(object);

I also i have ac# part to the application (for running a background task), that needs to read that JSON, and turn it into an object so i can iterate over it. 我也对应用程序有一个ac#部分(用于运行后台任务),它需要读取JSON,并将其转换为对象,以便可以对其进行迭代。 And this is where i am having some issues, i am using JSON.NET to do the work, but every thing i turn turns up with an error: 这是我遇到一些问题的地方,我正在使用JSON.NET进行工作,但是我发现的每件事都出现错误:

// this looks like "[{\"id\":1},{\"id\":2}]"
string exampleJSON = roaming.Values["example"].ToString();
// dont know if this is correct:
List<string> example = JsonConvert.DeserializeObject<List<string>>(exampleJSON );

That give an error of: 这给出了以下错误:

Error reading string. 读取字符串时出错。 Unexpected token: StartObject. 意外的令牌:StartObject。 Path '[0]', line 1, position 2. 路径“ [0]”,第1行,位置2。

So i am at a loss of what to do, i have been working on it for last few hours, and i am quite unfamiliar with c#, so resorting to the help of stackoverflow ;D 所以我无所适从,我已经工作了近几个小时,而且我对c#还是很陌生,所以请借助stackoverflow; D

Thanks in advance for any help :) 在此先感谢您的帮助:)

Andy 安迪

Json.Net has a nice method DeserializeAnonymousType . Json.Net有一个不错的方法DeserializeAnonymousType No need to declare a temporary class. 无需声明临时类。

string json = "[{\"id\":1},{\"id\":2}]";
var anonymous = new []{new{id=0}};
anonymous = JsonConvert.DeserializeAnonymousType(json,anonymous);

foreach (var item in anonymous)
{
    Console.WriteLine(item.id);
}

You can even use the dynamic keyword 您甚至可以使用dynamic关键字

dynamic dynObj = JsonConvert.DeserializeObject(json);
foreach (var item in dynObj)
{
    Console.WriteLine(item.id);
}

You are trying to parse your JSON array into a List of strings, which doesn't work. 您正在尝试将JSON数组解析为字符串列表,这是行不通的。 The JSON object you provide is actually a list of objects containing an integer property called 'id'. 您提供的JSON对象实际上是包含名为'id'的整数属性的对象列表。

Perhaps try creating a class (say, MyClass) with just that property, and deserialize into List. 也许尝试仅使用该属性创建一个类(例如,MyClass),然后反序列化为List。

Your json containts a collection of objects with an id property, something like this: 您的json包含具有id属性的对象的集合,如下所示:

class IdObject {
    public int id { get; set; }
}

You could then do: 然后,您可以执行以下操作:

JsonConvert.DeserializeObject<List<IdObject>>(exampleJSON);

Because the IdObject class has a property id to match your json serialized value, it will be mapped back. 由于IdObject类具有与您的json序列化值匹配的属性id ,因此将其映射回去。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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