我希望从WeatherAPI中读取数据http://www.aerisweather.com/support/docs/api/getting-started/responses/
它有几层深的数据。使用Json.Net时。我可以解析我的WebClient.DownloadData方法返回的字节数组。但是,即使在解析此字节数组之后,我的结果也是3个键值对,第三个键值对是由多个键值对组成的结果。
有关如何解决这个问题的任何想法。
我的代码如下:
var degrees = from d in context.GetTable<Employee>() select d;
foreach (var d in degrees)
{
d.Degree = String.Join(",", d.Degree
.Split(new String[] { "##" }, StringSplitOptions.None)
.Distinct());
}
context.SubmitChanges();
这是api调用返回的第三个值。
WebClient wc = new WebClient();
var stream = wc.DownloadData("http://api.aerisapi.com/observations/milwaukee,wi?client_id=" + id +
"&client_secret=" + secret + "");
Dictionary<string, Object> jsonStr = parse(stream);
Console.ReadLine();
}
public static Dictionary<String, Object> parse(byte[] stream)
{
string jsonStr = Encoding.UTF8.GetString(stream);
return JsonConvert.DeserializeObject<Dictionary<String, Object>>(jsonStr);
}
答案 0 :(得分:1)
如果您不想重新创建对象模型,可以使用动态JObject:
static void Main(string[] args)
{
using (var wc = new WebClient())
{
var stream = wc.DownloadData("http://api.aerisapi.com/observations/milwaukee,wi?client_id=xxx&client_secret=xxx");
dynamic jsonObject = Parse(stream);
Console.WriteLine(jsonObject.success);
Console.WriteLine(jsonObject.error);
Console.WriteLine(jsonObject.response);
Console.WriteLine(jsonObject.response.place.name);
}
Console.ReadLine();
}
public static JObject Parse(byte[] stream)
{
var jsonStr = Encoding.UTF8.GetString(stream);
return JObject.Parse(jsonStr);
}
答案 1 :(得分:0)
您应该创建一个相应的类(以及嵌套对象的其他类),然后创建它的实例并调用
JsonConvert.PopulateObject(jsonString, myObject);
根对象看起来像
public class AerisWeatherResponse
{
public bool success;
public AerisWeatherError error; // a class with code and description fields
public AerisWeatherResponseBody response;
}
AerisWeatherResponseBody类应如下所示:
public class AerisWeatherResponseBody
{
public string id;
public AerisWeatherLocation; // a class with long and lat fields
public AerisWeatherPlace; // a class with name, state and country fields
.......
.......
}