简体   繁体   中英

Parsing json with JSON.net on windows phone c#

I'm a novice developer for WP. I have some problems with parsing json data. I take it from the server and parse with JSON.Net.

Example of JSON data

{"response":
     {"ad6a95dd8f90fad7e281994cb5a8cacd":
           {"status":"offline", "name": "Test Name",
            "id":"ad6a95dd8f90fad7e281994cb5a8cacd"}
     }
 "success":true
}

The first chield of "response" varies with each request to the server. How I can extract value of "name" field ?! Thank you in advance for your reply.

I try that in Page.xaml.cs

var o = JObject.Parse(result);
        var id = o["response"].First;
        ServerList.ItemsSource = id;

and in Page.xaml

<ScrollViewer Foreground="White">
                        <ListBox Margin="0,0,-12,0" Name="ServerList" Height="508" Width="415">
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Margin="0,0,0,20" Width="300">
                                        <TextBlock Text="{Binding Path=name}" />
                                    </StackPanel>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>
                    </ScrollViewer>

I did it by example.

To get the name value from that Json I did this:

var o = JObject.Parse(result);
var id = o["response"].First.First["name"];
string name = id.Value<string>();

If you are actually trying to do this operation over an array of responses such as this:

{"responses":
    [
        {"response":
            {"ad6a95dd8f90fad7e281994cb5a8cacd":
                {"status":"offline", "name": "Test Name","id":"ad6a95dd8f90fad7e281994cb5a8cacd"} },"success":true },
        {"response":
            {"ad6a95dd8f90fad7e281994cb5a8cacd":
                {"status":"offline", "name": "Test Name2","id":"ad6a95dd8f90fad7e281994cb5a8cacd"} }, "success":true }
    ]
}

Then your code would need to look something like:

var o = JObject.Parse(result);
var ids = from c in o["responses"].Children() select c["response"].First.First;
var names = ids.Select(t => t.SelectToken("name").Value<string>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM