th3n3wguy
th3n3wguy

Reputation: 3737

JSON Parsing in Windows Phone 7

So, I have looked everywhere online and got a couple examples on how to parse JSON strings and then save that information into specific variables, but I am extremely new to C# and Windows Phone 7 development (only been doing it for a week, but I'm picking it up fast as I know C++ pretty well). I am having trouble understanding how I am supposed to approach this, so I will just give you the code that I want to parse and the code I have so far.

I have already validated my JSON information using the http://jsonlint.com/ Validator. Here is the JSON information (located on a website) that I want to parse:

[
    {
        "id": 19019,
        "model": "tester",
        "fields":
        {
            "name": "thename",
            "slot": 45,
            "category": "thecategory"
        }
    }
]

Here is the code that I am trying to use to parse the JSON information and store it as variables so that I can call that information later on in the program:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Resources;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace PhoneApp
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void myButton_Click(object sender, RoutedEventArgs e)
        {
            WebClient client = new WebClient();
            client.OpenReadCompleted += (s, eargs) =>
                {
                    var serializer = new DataContractJsonSerializer(typeof(RootObject));
                    var theItem = (RootObject)serializer.ReadObject(eargs.Result);
                    myTextBlock.Text = theItem.pk.ToString();
                };
            client.OpenReadAsync(new Uri("http://www.example.com/i/19019/json"));
        }
    }
    public class RootObject
    {
        public int pk { get; set; }
        public string model { get; set; }
        public Item item { get; set; }
    }
    public class Item
    {
        public string name { get; set; }
        public int slot { get; set; }
        public string category { get; set; }
    }
}

As far as this code is concerned, the myTextBlock is a text block in my Windows Phone 7 application that has the space to display the text and the myButton is the button that the user taps on to display the text (I am going to display the text differently once I get this fixed). Right now, whenever I launch this code, it initializes the application just fine, but then when I click on the button, it gives me an InvalidCastException was unhandled with specifics When casting from a number, the value must be a number less than infinity. error at the code:

var theItem = (RootObject)serializer.ReadObject(eargs.Result);

I hope I have given enough information to help me resolve this. I would prefer to use the libraries that are built into the Windows Phone 7 SDK by default, but if what I am trying to do would be much better handled using an external library like JSON.NET or others that are compatible, then I would be willing to learn if you provide me with the proper links to learn it. I appreciate any help you guys can give.

Cheers!

Upvotes: 3

Views: 8997

Answers (3)

M Jun
M Jun

Reputation: 19

Following Code is simple and complete code to get the response from Web using HTTP client and parse it :

 var httpClient = new HttpClient(new HttpClientHandler());

 var url ="http://www.example.com/i/19019/json";

 HttpResponseMessage response = await httpClient.GetAsync(url);

                    var data = response.Content.ReadAsStringAsync();

                    var result= JsonConvert.DeserializeObject<RootObject>(data.Result.ToString());

You can access data members as:

result.id; 

Upvotes: 0

Juozas Kontvainis
Juozas Kontvainis

Reputation: 9597

Here's a way to parse without external library

[DataContract]
public class InfoJson
{
    [DataMember]
    public int id { get; set; }

    public static InfoJson[] parseArray(String json)
    {
        var serializer = new DataContractJsonSerializer(typeof(InfoJson[]));

        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            return (InfoJson[]) serializer.ReadObject(ms);
        }
    }
}

Upvotes: 1

L.B
L.B

Reputation: 116108

You can deserialize your input string using Json.Net [sorry for external library :(] as below

var root = JsonConvert.DeserializeObject<RootObject[]>(inputString);

public class RootObject
{
    public int id { get; set; }
    public string model { get; set; }
    public Item fields { get; set; }
}
public class Item
{
    public string name { get; set; }
    public int slot { get; set; }
    public string category { get; set; }
}

EDIT >> Here is the full source code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace ConsoleApplication1
{
    public class MyClass
    {
        public static void Main(string[] args)
        {
            string inputString = @"
                [
                    {
                        ""id"": 19019,
                        ""model"": ""tester"",
                        ""fields"":
                        {
                            ""name"": ""thename"",
                            ""slot"": 45,
                            ""category"": ""thecategory""
                        }
                    }
                ]
            ";
            var root = JsonConvert.DeserializeObject<RootObject[]>(inputString);

            foreach (var item in root)
            {
                Console.WriteLine(item.id + " " + item.model + " " + item.fields.name + " " + item.fields.category);
            }
        }
    }

    public class RootObject
    {
        public int id { get; set; }
        public string model { get; set; }
        public Item fields { get; set; }
    }
    public class Item
    {
        public string name { get; set; }
        public int slot { get; set; }
        public string category { get; set; }
    }
}

Upvotes: 5

Related Questions