I have a json response like below code, and need to know how can i handle this with my current setup,
currently i can handle only one pair value-key response(id=type),
please refer the code i cant output these to a long list selector
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp5.Resources;
using Newtonsoft.Json;
namespace PhoneApp5
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
var definition1 = new { Name = "" };
var definition2 = new { id = "" }; //is that true? i want to pull inside the Table1
string json1 = #"{'Name':'James'}";
string json2 = #"{
'Table1': [
{
'id': 0,
'item': 'item 0'
},
{
'id': 1,
'item': 'item 1'
}
]
}";
var example1 = JsonConvert.DeserializeAnonymousType(json1, definition1);
var example2 = JsonConvert.DeserializeAnonymousType(json2, definition2);
MessageBox.Show(example2.id);
// ??? i need to do with a long list selector
}
}
}
As you edited your answer, you can do something like this:
public class MyClass
{
public string Id { get; set; }
public string Item { get; set; }
}
Then, do this:
var myClassList = JsonConvert.DeserializeObject<List<MyClass>>(e.Result);
longListSelector.ItemsSource = myClassList;
That way you're binding your class list to the LongListSelector Control.
Related
I'm getting this error...
Cannot implicitly convert type 'System.Threading.Tasks.Task System.Collections.Generic.List Thoughts.ViewModel.PickerViewModel.Location'** to **'System.Collections.Generic.List Thoughts.ViewModel.PickerViewModel.Location '
Anyone an idea?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Xamarin.Essentials;
namespace Thoughts.ViewModel
{
public class PickerViewModel
{
public List<Location> LocationsList { get; set; }
public class Location
{
public string name { get; set; }
}
public PickerViewModel()
{
LocationsList = GetLocations();
}
public async Task<JToken> GoogleApi()
{
var location = await Geolocation.GetLastKnownLocationAsync();
string locationString = location.Latitude.ToString() + "," + location.Longitude.ToString();
string radius = "2000";
string apiKey = "My_API_KEY";//Ofcourse its filled in
var httphelper = new HttpClient();
string link = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + locationString + "&radius=" + radius + "&key=" + apiKey;
var data = await httphelper.GetStringAsync(link);
var jsonData = JObject.Parse(data)["results"];
return jsonData;
}
public async Task<List<Location>> GetLocations()
{
JToken data = await GoogleApi();
var locationList = new List<Location>() { };
foreach (var location in data)
{
new Location() {name = location["name"].ToString() };
}
return locationList;
}
}
}
A Task<T> is a Task wrapper around a value. Normally, you would unwrap it using await.
However, in this case, the value you're unwrapping is something you want to display in a UI. So here you would want to have your constructor set up something to display in the meantime (an empty collection, or a "Loading..." indicator). Your constructor should then start an asynchronous operation that updates the data to display. This article goes into more details on this pattern.
I am working on a keyword search that looks for a part in two different sites. I have their api and I do get the response.The two responses have different JSONs and different variables in RootObject.
This causes the error
namespace OctopartApi
{
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine;
using System.Net;
using UnityEngine.UI;
public class KeywordSearch1 : MonoBehaviour
{
public InputField mainInputField;
public Canvas can;
public float x, y;
void Start () {
mainInputField.onEndEdit.AddListener(delegate {LockInput(mainInputField); });
}
void LockInput(InputField input)
{
ExecuteSearch (input.text);
}
public void ExecuteSearch(string inp)
{
// -- your search query --
string query = inp;
string octopartUrlBase = "http://octopart.com/api/v3";
string octopartUrlEndpoint = "parts/search";
string apiKey = "57af648b";
// Create the search request
var client = new RestClient(octopartUrlBase);
var req = new RestRequest(octopartUrlEndpoint, Method.GET)
.AddParameter("apikey", apiKey)
.AddParameter("q", query)
.AddParameter("start", "0")
.AddParameter("limit", "10");
// Perform the search and obtain results
var resp = client.Execute(req);
string octojson = resp.Content;
RootOb hh = JsonUtility.FromJson<RootOb> (octojson);// RootOb NOT FOUND ( but Root is recognized)
Manufacturer manufacturer = hh.manufacturer;//NOT FOUND
}
// -- your API key -- (https://octopart.com/api/register)
private const string APIKEY = "57af648b";
}
}
This is my model class
[System.Serializable]
public class RootOb
{
public string __class__;
public Brand brand;
public Manufacturer manufacturer;
public string mpn;
public string octopart_url;
public List<Offer> offers;
public List<string> redirected_uids;
public string uid;
}
How I access the response in the second class
Root res = JsonUtility.FromJson<Root>(jsonString);//No issues here
For some reason , I am able to access only Root and not RootOb.What am I doing wrong ?
The type or namespace name `RootOb' could not be found. Are you missing an assembly reference?
Edit : I tried deleting the Root class,and now RootOb gets detected! Should there be only one def of JsonUtility?
To break it down, this is my first time using ASP.NET Web Api. I am trying to just get simple tasks down and then from there I will understand more things and be able to work with it, I just need a starting ground. So to begin a simple task for me would be to get a list of Users in a database.
I want the JSON result do something like return an object called Repsonse that holds an array of User objects, with each User object storing just like a first and last name. Please anything that can help me understand how to achieve what I am looking for would be appreciated. List code samples can be viewed at api.holybreadstick.com/api/users
Really would be okay if this would return the information without the k_BackingField? If that can be resolved that will help a lot.
This is my ResponseController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace PublicWebApi.Controllers
{
public class UsersController : ApiController
{
Response response = new Response();
public Response GetAllUsers()
{
return response;
}
}
}
This is my Response.cs class
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Collections.Generic;
namespace PublicWebApi
{
public class Response
{
public List<User> Data = new List<User>();
public Response()
{
allReturn();
}
public void allReturn()
{
for (int x = 0; x < 5; x++)
{
User objet = new User("Bailey", x);
Data.Add(objet);
}
}
}
[Serializable()]
public class User
{
public String name { get; set; }
public int id { get; set; }
public User(String n, int id)
{
name = n;
this.id = id;
}
}
}
So right now this is my result I am getting in JSON.
{
"Data": [
{
"<name>k__BackingField": "Bailey",
"<id>k__BackingField": 0
},
{
"<name>k__BackingField": "Bailey",
"<id>k__BackingField": 1
},
{
"<name>k__BackingField": "Bailey",
"<id>k__BackingField": 2
},
{
"<name>k__BackingField": "Bailey",
"<id>k__BackingField": 3
},
{
"<name>k__BackingField": "Bailey",
"<id>k__BackingField": 4
}
]
}
Hello i am currently in the infant stages of writing a petshop app on Windows phone/C#. I have made the class below to set up my generic lists and to be able to add the pets to the shop using the given fields ( Name, age, breed and type ). The problem i believe lies in the fact that i am making a display method to be called (in another page which is below called Mainpage.xaml.cs) below called DisplayShop() and i am reading in 3 strings and an int, i believe it has something to do with the fact that my DisplayShop() method is a string, although i tried to rectify the problem by converting the age field to a string in the Display() method, although this has not fixed the problem.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assignment_1
{
public class Shop
{
private string name;
private int age;
private string breed;
private string type;
public Shop(string Name, int Age, string breed, string Type)
{
this.Name = name;
this.Age = age;
this.breed = breed;
this.Type = type;
}
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
public int Age
{
get
{
return this.age;
}
set
{
this.age = value;
}
}
public string Breed
{
get
{
return this.breed;
}
set
{
this.breed = value;
}
}
public string Type
{
get
{
return this.type;
}
set
{
this.type = value;
}
}
//Create the Collection
List<Shop> myShop = new List<Shop>();
public String Display()
{
return (Name + "\n" + Age.ToString() + "\n" + Breed + "\n" + Type);
}
public String DisplayShop()
{
foreach (Shop tmp in myShop)
{
tmp.Display();
}
}
}
}
Here is the Mainpage.xaml.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
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 Microsoft.Phone.Controls;
namespace Assignment_1
{
public partial class MainPage : PhoneApplicationPage
{
List<Shop> myShop = new List<Shop>();
// Constructor
public MainPage()
{
InitializeComponent();
setUpShop();
}
//Add animals to the Shop
private void setUpShop()
{
myShop.Add(new Shop("John", 3 ,"Labrador", "Dog"));
myShop.Add(new Shop("Billy", 9, "Terrier", "Dog"));
myShop.Add(new Shop("Sam", 2, "Persian", "Cat"));
myShop.Add(new Shop("Molly", 3, "Siamese", "Cat"));
myShop.Add(new Shop("Nemo", 1, "Clown Fish", "Fish"));
myShop.Add(new Shop("Dory", 1, "Palette Surgeonfish", "Fish"));
myShop.Add(new Shop("Keith", 1, "Bearded Dragon", "Lizard"));
myShop.Add(new Shop("Ozzy", 1, "Gecko", "Lizard"));
imgHolder1.Items.Add(myShop[1].DisplayShop());
}
}
}
The aim of this first part is to add the pets to an listBox in my windows app, if any of you could suggest a fix to this problem it would be much appreciated, I have included an image of the the way the phone app currently looks >>> http://gyazo.com/06217efae9265d0fef59cd2a44be7923 and the error code >>> http://gyazo.com/40c47628f1dfb7d735af4c72dde3a651
Thanks in advance,
Jason
Looks like you forgot to return value from DisplayShop funcion:
public String DisplayShop()
{
List<string> shops = new List<string>();
foreach (Shop tmp in myShop)
{
shops.Add(tmp.Display());
}
return string.Join(",", shops);
}
Join used here just to show the general idea, you can use whatever you want to construct the whole string.
You are not returning anything from this function:
public String DisplayShop()
You should return a string from it, or just change return type to void if you don't want to return anything:
public void DisplayShop()
Update:
imgHolder1.Items.Add(myShop[1].DisplayShop());
In this line you are calling DisplayShop on a Shop instance,but you didn't add any elements to the list that is inside of the Shop class.You create a seperate list.So in this case even if it works myShop[1].DisplayShop() won't display anything because your initial myShop list is empty.If you want to display one Shop just call your Display method.Anyway,probably you don't need that initial list, if you want to add all Shops to the listBox then use a simple foreach loop:
foreach(var shop in myShop)
{
imgHolder1.Items.Add(shop.Display());
}
public String DisplayShop()
{
foreach (Shop tmp in myShop)
{
tmp.Display();
}
}
your return type is a String but you aren't returning anything. Not all code paths return a value is telling you exactly that
I'm not sure how to create a list of objects. I get "Non-invocable member ListObjects.TestObject.UniqueID' cannot be used like a method."
Any insight would be helpful.
The code for the object I'm trying to create a list of:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListObjects
{
class TestObject
{
public int UniqueID { get; set; }
}
}
Main code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListObjects
{
class Program
{
static void Main(string[] args)
{
TestObject TestObject = new TestObject();
List<TestObject> ObjectList = new List<TestObject>();
ObjectList.Add(new TestObject().UniqueID(1));
ObjectList.Add(new TestObject().UniqueID(10));
ObjectList.Add(new TestObject().UniqueID(39));
}
}
}
public int UniqueID { get; set; } is not a method its a setter and you use it like a method
do this
ObjectList.Add(new TestObject()
{
UniqueID = 1
});
I cannot rememer the syntax but it is from memory:
repalce this line:
ObjectList.Add(new TestObject().UniqueID(1));
with this line:
ObjectList.Add(new TestObject(){UniqueID = 1});
and do the same for all .Add lines you have.
You are using UniqueId like a method. It is a property and must be assigned. If you know you'll be assigning an ID when creating a TestObject, you should make the constructor support that, and use it accordingly. If not, use ObjectList.Add(new TestObject { UniqueID = 1 }); to assign the value without a constructor.
This is how I would handle the situation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListObjects
{
class TestObject
{
public int UniqueID { get; set; }
public TestObject(int uniqueId)
{
UniqueID = uniqueId;
}
}
}
Main code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListObjects
{
class Program
{
static void Main(string[] args)
{
List<TestObject> ObjectList = new List<TestObject>();
ObjectList.Add(new TestObject(1));
ObjectList.Add(new TestObject(10));
ObjectList.Add(new TestObject(39));
}
}
}
There's a couple of things going on here. You don't need an instance of the object to declare the list, just the type.
Also, UniqueID is a property, not a method. You assign values to them (or read values from them), you don't pass in values like a parameter for a method.
You can also initialize the list in one call, like this:
List<TestObject> ObjectList = new List<TestObject>()
{ new TestObject() { UniqueID = 1},
new TestObject() { UniqueID = 10 },
new TestObject() { UniqueID = 39 } };
This will result in a new List<T> where T is of type TestObject, and the list is initialized to 3 instances of TestObject, with each instance initialized with a value for UniqueID.
TestObject TestObject = new TestObject();
Remove this line.
And edit following lines to this syntax
new TestObject { UniqueID = 39 }