所以我目前正在尝试反序列化JSON API。 我使用的代码与我成功用于其他API的代码相同。 但每个变量只返回0.
public class RootObject
{
public int lat { get; set; }
public int lon { get; set; }
public DateTime date_iso { get; set; }
public int date { get; set; }
public double value { get; set; }
}
public class UVGetter
{
public static async Task<RootObject> UVApiProxy(double lat, double lon)
{
var Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
var http = new HttpClient();
string WeatherApiKey = "secret";
var url = String.Format($"https://api.openweathermap.org/data/2.5/uvi/history?appid=" + WeatherApiKey + "&lat=" + Math.Round(lat) + "&lon=" + Math.Round(lon) + "&start=" + Timestamp + "&end=" + Timestamp);
var response = await http.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof(RootObject));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var uvdata = (RootObject)serializer.ReadObject(ms);
Agara.Program.WeatherApiCalls++;
Console.WriteLine(uvdata.lat + "\n" + uvdata.lon + "\n" + uvdata.date_iso.ToString() + "\n" + uvdata.date + "\n" + uvdata.value);
return uvdata;
}
}
结果如下所示
[{"lat":54,"lon":9,"date_iso":"2018-05-08T12:00:00Z","date":1525780800,"value":5.62}]
变量(例如uvdata.lat)只包含零,尽管API信息应该存储在那些中。
答案 0 :(得分:3)
JSON不包含RootObject
,它是RootObject
的数组。所以:
var serializer = new DataContractJsonSerializer(typeof(RootObject[]))
// ...
var uvdata = (RootObject[])serializer.ReadObject(ms);
或者,使用Newtonsoft.Json:
var uvData = JsonConvert.DeserializeObject<RootObject[]>(result);
您也可以反序列化为List<RootObject>
而不是数组。
如果要保留前导零,请将这些属性反序列化为字符串,因为整数没有这个概念,所以:
public class RootObject
{
public string lat { get; set; }
public string lon { get; set; }
public DateTime date_iso { get; set; }
public int date { get; set; }
public double value { get; set; }
}
答案 1 :(得分:0)
您的json字符串是一个数组而不是单个对象,因此您应该反序列化为数组。您也可以使用Newtonsoft.Json
(即使它很容易使用),只需复制json字符串并在VisualStudio中轻松创建android {
compileSdkVersion 25
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "com.example.app"
minSdkVersion 15
targetSdkVersion 24
versionCode 9
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
编辑 - &gt; PasteSpecial - &gt;将JSON粘贴为类
class