转换json数据以在xamarin中反序列化对象时出现问题 [英] Problem in convert json data to deserialize object in xamarin

查看:142
本文介绍了转换json数据以在xamarin中反序列化对象时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换它并在visual studio中使用xamarin在文本框中显示。

how to convert this and shown in textbox using xamarin in visual studio.

return JsonConvert.DeserializeObject<string>(result);



这是完整的代码。


this is the complete code.

string url = @"http://api.wunderground.com/api/02e5dd8c34e3e657/geolookup/conditions/forecast/q/Dhaka,Bangladesh.json";
            using (var client = new HttpClient())
            {
                var result =client.GetStringAsync(url);
                return JsonConvert.DeserializeObject<string>(result);
            }

推荐答案

Note: I don't use Xamarin/Mono, but the code shown here works in Visual Studio 2013, .NET FrameWork 4.5, as long as the project has a reference to NewtonSoft JSON, and I assume it will work, as is, in Xamarin: if it doesn't, then ask Xamarin for support.

您当前代码出现问题:我怀疑您没有正确使用异步;你可以通过在'return JsonConvert'开头的行上放置一个断点来检查'结果'的内容。



其次,它确实没有任何意义尝试将JSON反序列化为strin g:JSON是对象格式,其反序列化输出是一个类的实例... case包含包含数据的其他类的实例的类。



您需要为解串器提供适当的类定义/模板以插入其数据到它将创建的类的实例。



幸运的是,很容易获得WeatherUnderground JSON API的C#类定义:转到JSONToCSharp站点[ ^ ],并粘贴到您的WU网址,按生成,然后复制它为您生成的类。



以下是我使用孟加拉国URI下拉数据所做的工作:



0.在Visual Studio中创建了一个新的公共类,我将其命名为WU_JSON

1.转到JSONToCSharp

2.粘贴在你的网址

3.按'生成并复制创建的类定义

4.将类定义粘贴到我的类WU_JSON的主体中



5.使用以下代码

Problem with your current code: I suspect that you are not using asynch properly; you can verify that by putting a break-point on the line starting with 'return JsonConvert, and examining the contents of 'result.

Second, it does not make any sense to try and de-serialize JSON into a string: JSON is an object-format and its de-serialize output is an instance of a Class ... in this case a Class containing instances of other Classes containing the data.

You need to supply the deserializer with a proper Class definition/template to "plug-in its data" to an instance of the Class it will create.

Fortunately, it's easy to get the C# class definition for the WeatherUnderground JSON API: go to the JSONToCSharp site [^], and paste in your WU url, press 'Generate, and copy the classes that it produces for you.

Here's exactly what I did to pull down the data using your Bangladesh URI:

0. created a new public Class in Visual Studio which I named WU_JSON
1. went to JSONToCSharp
2. pasted in your url
3. pressed 'Generate and copied the Class definitions created
4. pasted the class definitions into the body of my Class WU_JSON

5. used the following code

// make sure you have these
using System.Linq;
using System.IO;
using System.Net;
using System.Xml;
using Newtonsoft.Json;

private WU_JSON.RootObject Parse_WU_JSON(string targetURI)
{
    Uri uri = new Uri(targetURI);

    var webRequest = WebRequest.Create(uri);
    WebResponse response = webRequest.GetResponse();

    WU_JSON.RootObject wUData = null;

    try
    {
        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            var responseData = streamReader.ReadToEnd();
            
            // if you want all the "raw data" as a string
            // just use: responseData.ToString()

            wUData = JsonConvert.DeserializeObject<wu_json.rootobject>(responseData);
        }
    }
    catch (Exception e)
    {
        // error occurred ... ???
    }
    
    return wUData;
}

// sample usage:

string wuUri = @"http://api.wunderground.com/api/02e5dd8c34e3e657/geolookup/conditions/forecast/q/Dhaka,Bangladesh.json";

WU_JSON.RootObject WU_Result = Parse_WU_JSON(wuUri);

if (WU_Result != null)
{
    // do something with the data in WU_Result
}
else
{
    // there was a problem getting the data
}</wu_json.rootobject>

你会注意到,在上面的代码中,注释掉了,是一个如何从字符串中获取WU的完整响应的解决方案。



FootNote:这是JSONToCSharp网站为我生成的整个WeatherUnderground JSON结构,但请注意,这种格式可能会有所变化,所以在使用之前先检查网站是一件好事:

You'll note that in the code above, commented out, is a solution for how to get the complete response from WU in a string.

FootNote: here's the entire WeatherUnderground JSON structure that the JSONToCSharp site generated for me, but note, that the format of this may be subject to change, so it's a good thing to check the site first before using this:

public class WU_JSON
{
    public class Features
    {
        public int geolookup { get; set; }
        public int conditions { get; set; }
        public int forecast { get; set; }
    }

    public class Response
    {
        public string version { get; set; }
        public string termsofService { get; set; }
        public Features features { get; set; }
    }

    public class Station
    {
        public string city { get; set; }
        public string state { get; set; }
        public string country { get; set; }
        public string icao { get; set; }
        public string lat { get; set; }
        public string lon { get; set; }
    }

    public class Airport
    {
        public List<Station> station { get; set; }
    }

    public class Pws
    {
        public List<object> station { get; set; }
    }

    public class NearbyWeatherStations
    {
        public Airport airport { get; set; }
        public Pws pws { get; set; }
    }

    public class Location
    {
        public string type { get; set; }
        public string country { get; set; }
        public string country_iso3166 { get; set; }
        public string country_name { get; set; }
        public string state { get; set; }
        public string city { get; set; }
        public string tz_short { get; set; }
        public string tz_long { get; set; }
        public string lat { get; set; }
        public string lon { get; set; }
        public string zip { get; set; }
        public string magic { get; set; }
        public string wmo { get; set; }
        public string l { get; set; }
        public string requesturl { get; set; }
        public string wuiurl { get; set; }
        public NearbyWeatherStations nearby_weather_stations { get; set; }
    }

    public class Image
    {
        public string url { get; set; }
        public string title { get; set; }
        public string link { get; set; }
    }

    public class DisplayLocation
    {
        public string full { get; set; }
        public string city { get; set; }
        public string state { get; set; }
        public string state_name { get; set; }
        public string country { get; set; }
        public string country_iso3166 { get; set; }
        public string zip { get; set; }
        public string magic { get; set; }
        public string wmo { get; set; }
        public string latitude { get; set; }
        public string longitude { get; set; }
        public string elevation { get; set; }
    }

    public class ObservationLocation
    {
        public string full { get; set; }
        public string city { get; set; }
        public string state { get; set; }
        public string country { get; set; }
        public string country_iso3166 { get; set; }
        public string latitude { get; set; }
        public string longitude { get; set; }
        public string elevation { get; set; }
    }

    public class Estimated
    {
    }

    public class CurrentObservation
    {
        public Image image { get; set; }
        public DisplayLocation display_location { get; set; }
        public ObservationLocation observation_location { get; set; }
        public Estimated estimated { get; set; }
        public string station_id { get; set; }
        public string observation_time { get; set; }
        public string observation_time_rfc822 { get; set; }
        public string observation_epoch { get; set; }
        public string local_time_rfc822 { get; set; }
        public string local_epoch { get; set; }
        public string local_tz_short { get; set; }
        public string local_tz_long { get; set; }
        public string local_tz_offset { get; set; }
        public string weather { get; set; }
        public string temperature_string { get; set; }
        public int temp_f { get; set; }
        public int temp_c { get; set; }
        public string relative_humidity { get; set; }
        public string wind_string { get; set; }
        public string wind_dir { get; set; }
        public int wind_degrees { get; set; }
        public int wind_mph { get; set; }
        public int wind_gust_mph { get; set; }
        public int wind_kph { get; set; }
        public int wind_gust_kph { get; set; }
        public string pressure_mb { get; set; }
        public string pressure_in { get; set; }
        public string pressure_trend { get; set; }
        public string dewpoint_string { get; set; }
        public int dewpoint_f { get; set; }
        public int dewpoint_c { get; set; }
        public string heat_index_string { get; set; }
        public string heat_index_f { get; set; }
        public string heat_index_c { get; set; }
        public string windchill_string { get; set; }
        public string windchill_f { get; set; }
        public string windchill_c { get; set; }
        public string feelslike_string { get; set; }
        public string feelslike_f { get; set; }
        public string feelslike_c { get; set; }
        public string visibility_mi { get; set; }
        public string visibility_km { get; set; }
        public string solarradiation { get; set; }
        public string UV { get; set; }
        public string precip_1hr_string { get; set; }
        public string precip_1hr_in { get; set; }
        public string precip_1hr_metric { get; set; }
        public string precip_today_string { get; set; }
        public string precip_today_in { get; set; }
        public string precip_today_metric { get; set; }
        public string icon { get; set; }
        public string icon_url { get; set; }
        public string forecast_url { get; set; }
        public string history_url { get; set; }
        public string ob_url { get; set; }
        public string nowcast { get; set; }
    }

    public class Forecastday
    {
        public int period { get; set; }
        public string icon { get; set; }
        public string icon_url { get; set; }
        public string title { get; set; }
        public string fcttext { get; set; }
        public string fcttext_metric { get; set; }
        public string pop { get; set; }
    }

    public class TxtForecast
    {
        public string date { get; set; }
        public List<Forecastday> forecastday { get; set; }
    }

    public class Date
    {
        public string epoch { get; set; }
        public string pretty { get; set; }
        public int day { get; set; }
        public int month { get; set; }
        public int year { get; set; }
        public int yday { get; set; }
        public int hour { get; set; }
        public string min { get; set; }
        public int sec { get; set; }
        public string isdst { get; set; }
        public string monthname { get; set; }
        public string monthname_short { get; set; }
        public string weekday_short { get; set; }
        public string weekday { get; set; }
        public string ampm { get; set; }
        public string tz_short { get; set; }
        public string tz_long { get; set; }
    }

    public class High
    {
        public string fahrenheit { get; set; }
        public string celsius { get; set; }
    }

    public class Low
    {
        public string fahrenheit { get; set; }
        public string celsius { get; set; }
    }

    public class QpfAllday
    {
        public double @in { get; set; }
        public int mm { get; set; }
    }

    public class QpfDay
    {
        public double @in { get; set; }
        public int mm { get; set; }
    }

    public class QpfNight
    {
        public double @in { get; set; }
        public int mm { get; set; }
    }

    public class SnowAllday
    {
        public double @in { get; set; }
        public double cm { get; set; }
    }

    public class SnowDay
    {
        public double @in { get; set; }
        public double cm { get; set; }
    }

    public class SnowNight
    {
        public double @in { get; set; }
        public double cm { get; set; }
    }

    public class Maxwind
    {
        public int mph { get; set; }
        public int kph { get; set; }
        public string dir { get; set; }
        public int degrees { get; set; }
    }

    public class Avewind
    {
        public int mph { get; set; }
        public int kph { get; set; }
        public string dir { get; set; }
        public int degrees { get; set; }
    }

    public class Forecastday2
    {
        public Date date { get; set; }
        public int period { get; set; }
        public High high { get; set; }
        public Low low { get; set; }
        public string conditions { get; set; }
        public string icon { get; set; }
        public string icon_url { get; set; }
        public string skyicon { get; set; }
        public int pop { get; set; }
        public QpfAllday qpf_allday { get; set; }
        public QpfDay qpf_day { get; set; }
        public QpfNight qpf_night { get; set; }
        public SnowAllday snow_allday { get; set; }
        public SnowDay snow_day { get; set; }
        public SnowNight snow_night { get; set; }
        public Maxwind maxwind { get; set; }
        public Avewind avewind { get; set; }
        public int avehumidity { get; set; }
        public int maxhumidity { get; set; }
        public int minhumidity { get; set; }
    }

    public class Simpleforecast
    {
        public List<Forecastday2> forecastday { get; set; }
    }

    public class Forecast
    {
        public TxtForecast txt_forecast { get; set; }
        public Simpleforecast simpleforecast { get; set; }
    }

    public class RootObject
    {
        public Response response { get; set; }
        public Location location { get; set; }
        public CurrentObservation current_observation { get; set; }
        public Forecast forecast { get; set; }
    }
}


Hi Satheesh,



Please see below the code used for converting Student JSON format string to Student Class..in Xamarin.



Class Library



Hi Satheesh,

Please see below the code used for converting Student JSON format string to Student Class..in Xamarin.

Class Library

using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;





Code for De- Serialization





Code for De- Serialization

public static T Deserialize<T>(string json) {
           var obj = Activator.CreateInstance<T>();
           using (var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json))) {
               var serializer = new DataContractJsonSerializer(obj.GetType());
               obj = (T) serializer.ReadObject(memoryStream);
               return obj;
           }
       }







The de-serialize function can be called by...




The de-serialize function can be called by...

StudentList = Deserialise<list>< Student >> (JsonString);
</list>


这篇关于转换json数据以在xamarin中反序列化对象时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆