0

I am beginner to C# Windows Phone programming. I am developing an app in which I am getting a JSON response from the site using web client but I don't know how to parse it.
Could you help me from this?

Code:

public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void btnRefreshTweets_Click(object sender, RoutedEventArgs e)
        {
            string winPhoneGeekTweetsUrl = @"http://ffff.xxxx.nxt/wpjson.php";

            WebClient webClient = new WebClient();
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            webClient.DownloadStringAsync(new Uri(winPhoneGeekTweetsUrl));
        }

        void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                return;
            }
            MessageBox.Show(e.Result );//-->this is where JSON response is displayed


          }
    }

wpjson.php

<?php
mysql_connect("mysql2.000webhost.com","12345","12345");
mysql_select_db("a1111111_forms");
$sql=mysql_query("SELECT * FROM newstable");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
    echo json_encode($output);
?>

I also wanted it to be displayed in list.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Vinod Kumar
  • 337
  • 5
  • 19

2 Answers2

2

Use http://json2csharp.com/ for create your JsonClasse

Or use visual studio => edit => special past

And use Newtonsoft.Json.JsonConvert.DeserializeObject<jsonClass>(result);

MatDev8
  • 976
  • 5
  • 18
1

Copy all the json.

Make new class of any name, say it "jsonClass" and in that class goto edit->paste special-> paste json as class.

Visual Studio will automatically generate class for you according to your json string.

OR

You can right it manually according to your json string.

Get your json string in a variable name it result.

jsonClass posts2 = Newtonsoft.Json.JsonConvert.DeserializeObject<jsonClass>(result.ToString());

It will map your json string into C# object.

Yawar
  • 1,924
  • 3
  • 29
  • 39
  • I am getting JSON data dynamically – Vinod Kumar Mar 21 '14 at 11:44
  • there must be a specific pattern in it. for example on first call i get this string { "id": "1492292372", "first_name": "Yawar" } and on second i get this { "id": "1492292372", "last_name": "Yawar" } So my class will be like this public class jsonClass {string id {get; set;} string first_name {get; set;} string last_name {get; set;} } – Yawar Mar 21 '14 at 11:50
  • NewtonSoft will automatically map string according to the names, so you should name the variables same. – Yawar Mar 21 '14 at 11:55
  • done all how to display it – Vinod Kumar Mar 21 '14 at 12:00
  • Simply handle it like C# objects. – Yawar Mar 21 '14 at 12:18