What is the simplest way to interact with a RESTful web service that deals in JSON? I see that WWWForm will let me GET and POST to a web service and that I could use litJSON to encode and parse my data, but litJSON doesn’t seem to have been maintained in a while.
How do Unity developers usually do this? Is there a Unity analogue of Resty for Objective-C?
Update: Now, it’s better to use unity’s UnityWebRequest for requests. For simple serialization you can use unity’s JsonUtility. Though, if you want incapsulation, you may want accessors (public get, private set). Then you can choose something from the web. There are plenty of serializers. Newtonsoft Json and GitHub - neuecc/Utf8Json: Definitely Fastest and Zero Allocation JSON Serializer for C#(NET, .NET Core, Unity, Xamarin). can do. Not tried them though, still have to maintain legacy codebase with legacy simplejson serializer.
Below is my original answer, written in 2017:
I am using RestSharp with success for android, iOs, Windows, Mac OS platforms. There is a fork of RestSharp which fixes some issues so that RestSharp works for Unity GitHub - eamonwoortman/RestSharp.Unity: A RestSharp fork focussed on support for Unity3D. It’s cool because you can use DesirializeAs attibute and use any names for fields, even with spaces. Example:
public class PurchasedProductResponse
{
[DeserializeAs(Name = "product id")]
public string ProductId { get; set; }
[DeserializeAs(Name = "rewards")]
public List<MoneyPrizeResponse> MoneyPrizes { get; set; }
}
public class MoneyPrizeResponse
{
[DeserializeAs(Name = "bonusData.imageUrl")]
public string ImageUrl { get; set; }
}
We’ve created our REST SDK on the shoulders of UnityHTTP. It provides API similar to restangular, implements path building, error handling, and other useful things. You can find it here: GitHub - vedi/restifizer-unity3d: Restifizer SDK for Unity3d
For example it allows something like that:
RestifizerManager.ResourceAt("api/users").
WithBearerAuth().
One(userId).
Patch(parameters, (response) => {
// response.Resource - at this point you can use the result
});
I’ve used JsonFx, which has worked great. Get it here
As for talking to the web service, you could go with WWW, but be ware that it does not support headers for GET requests. You could write your own solution using sockets, or do what I did and grab uniweb. Hope that helps.
I’ve been using UnityHTTP, which has been super simple to set up and gives me the “PUT” verb, though it hasn’t been without its problems. Your code ends up looking something like this:
HTTP.Request theRequest = new HTTP.Request( "PUT", myUrl, lightSettings ); // build the request
theRequest.Send(); // send the request
Where “myUrl” is a string and “lightSettings” is a hashtable.