Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Parsing in Windows Phone 7

Tags:

json

c#

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!

like image 986
th3n3wguy Avatar asked Jan 23 '26 23:01

th3n3wguy


2 Answers

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; }
    }
}
like image 149
L.B Avatar answered Jan 25 '26 13:01

L.B


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);
        }
    }
}
like image 36
Juozas Kontvainis Avatar answered Jan 25 '26 12:01

Juozas Kontvainis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!