This question already has answers here:
Serialize and Deserialize Json and Json Array in Unity
(9 answers)
Closed 5 years ago.
I am new in unity and I need to download data from JSON. I successfully download JSON data but I am not able to parse the JSON. I have use Boomlagoon Asset to serialize my JSON. Here is my code.
void Start() {
string url = "http://www.windmillinfotech.com/carlife/carlife_api/get_workshop";
WWWForm form = new WWWForm();
form.AddField("district", "Dhaka");
form.AddField("thana", "Mirpur");
form.AddField("service_type", "car");
WWW www = new WWW( url, form );
StartCoroutine (request(www));
}
IEnumerator request (WWW www) {
yield return www;
if(!string.IsNullOrEmpty(www.error)) {
print( "Error : " + www.error );
} else {
string serviceData = www.text;
JSONObject json = JSONObject.Parse(serviceData);
print ("\n\n\n\n"+json["workshop_dtls_result"]);
}
}
and my JSON result is like follows,
{
"success": true,
"workshop_dtls_result": [
{
"id": "141",
"user_id": "",
"store_id": null,
"updated_by": null,
"workshop_name": "Okay Auto Engineering",
"workshop_email": "",
"workshop_address": "Section -10, Block - A, Plot - 9, Main Road, Mirpur, Dhaka-1216. Behind the graveyard, 01712978222",
"district": "Dhaka",
"thana": "Mirpur",
"post_code": "",
"contact_person": "Sabir Hossain",
"contact_number": "01712978222",
"alternative_number": "",
"service_type_car": "Car",
"service_type_bus": "",
"service_type_bike": "",
"workshop_photo_1": "",
"workshop_photo_2": "",
"workshop_photo_3": "",
"latitude": "",
"longitude": "",
"create_date": "2017-01-01",
"active_status": "Active",
"workshop_services": null,
"lubricants_available": "No",
"lubricant_products": null
},
{
"id": "142",
"user_id": "",
"store_id": null,
"updated_by": null,
"workshop_name": "Ali Automobile ",
"workshop_email": "",
"workshop_address": "Section -11, Block- D, Avenue-1 Plot-14, Mob: 01925920115",
"district": "Dhaka",
"thana": "Mirpur",
"post_code": "",
"contact_person": "Mohammad Ali",
"contact_number": "01925920115",
"alternative_number": "",
"service_type_car": "Car",
"service_type_bus": "",
"service_type_bike": "",
"workshop_photo_1": "",
"workshop_photo_2": "",
"workshop_photo_3": "",
"latitude": "",
"longitude": "",
"create_date": "2017-01-01",
"active_status": "Active",
"workshop_services": null,
"lubricants_available": "No",
"lubricant_products": null
}
]
}
Now my question is that how can I get each values of id, workshop_name etc? Please help me to parse this JSON data.
Thanks in advance.
Please refer to below code as reference:
using SimpleJSON;
var N = JSON.Parse(the_JSON_string);
var versionString = N["version"].Value; // versionString will be a string containing "1.0"
var versionNumber = N["version"].AsFloat; // versionNumber will be a
float containing 1.0
var name = N["data"]["sampleArray"][2]["name"];// name will be a string containing "sub object"
Here the JSON string (the_JSON_string) is as follows:
{
"version": "1.0",
"data": {
"sampleArray": [
"string value",
5,
{
"name": "sub object"
}
]
}
}
Note that according to our experience, SimpleJson works on both Android and iOS, and NewtonSoft does NOT work in some iOS devices. If your app is mobile app, you should not use NewtonJson.
Add Newtonsoft.Json from nuGet package manager to your solution.
Add reference inside the unity file
in server side serialize your list like: JsonConvert.SerializeObject(your object);
in client side do like this : JSON.Parse(your result)
Related
With this code:
var button = Value.ForStruct(new Struct{
Fields={
["type"] = Value.ForString("postback"),
["title"] = Value.ForString("Call Representative"),
["payload"] = Value.ForString("+15105551234"),
}
});
var inPayload = Value.ForStruct(new Struct{
Fields ={
["buttons"] = Value.ForList(button),
["text"] = Value.ForString("try the postback"),
["template_type"] = Value.ForString("button"),
}
});
var attachment = Value.ForStruct(new Struct{
Fields ={
["payload"] = inPayload,
["type"] = Value.ForString("template"),
}
});
var msg = Value.ForStruct(new Struct{
Fields ={
["attachment"] = attachment,
});
Payload = new Struct{
Fields ={
["facebook"] = msg
}
I was able to create the following json:
"payload": {
"facebook": {"attachment": {
"payload": {
"buttons": [ {
"type": "postback",
"title": "Call Representative",
"payload": "+15105551234"
}],
"text": "try the postback",
"template_type": "button"
},
"type": "template"
}}
Now I need to create the following other format but I dont find how to do it:
"payload": {
"message": "Yes I did it"
"platform": "kommunicate",
"attachment": {
"payload": {
"buttons": [ {
"type": "postback",
"title": "Call Representative",
"payload": "+15105551234"
}],
"text": "try the postback",
"template_type": "button"
},
"type": "template"
}
I really dont find how to eliminate the first "facebook": { element and leave only:
{
"message": "Yes I did it",
"platform": "kommunicate",
"attachment":
And include message and platform at the same level. Here is the complete json I will like to generate:
"payload": {
"platform": "kommunicate",
"message": "Yes I did it",
"attachment": {
"payload": {
"buttons": [ {
"type": "postback",
"title": "Call Representative",
"payload": "+15105551234"
}],
"text": "try the postbackggggggg",
"template_type": "button"
},
"type": "template"
}
If you want to take an object and convert it to json I would recommend taking a look at Newtonsoft Json.Net library. They have plenty of examples that might help you. There is also protobuf.net library for serializing to protobuf instead of json.
Both libraries are used in similar ways, you create a class with appropriate properties and set the values you want. You will need multiple classes for nested types as in your example. Protobuf requires you to annotate the properties with attributes, while this is optional for json.net. You then send the object to the serialization library and get a string or binary data representing your object. This kind of object is often called a Data Transfer Object (DTO), since the only purpose it has is to aid in serialization or/and transfering the data to another system.
Could someone give me a hint as to the class structure to use to deserialise this Json response from the Wikipedia opensearch api:
[
"test",
[
"Test",
"Testosterone",
"Test (assessment)",
"Testicle",
"Test-driven development",
"Testosterone (medication)",
"Testicular cancer",
"Test cricket",
"Tests of general relativity",
"Test (wrestler)"
],
[
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
],
[
"https://en.wikipedia.org/wiki/Test",
"https://en.wikipedia.org/wiki/Testosterone",
"https://en.wikipedia.org/wiki/Test_(assessment)",
"https://en.wikipedia.org/wiki/Testicle",
"https://en.wikipedia.org/wiki/Test-driven_development",
"https://en.wikipedia.org/wiki/Testosterone_(medication)",
"https://en.wikipedia.org/wiki/Testicular_cancer",
"https://en.wikipedia.org/wiki/Test_cricket",
"https://en.wikipedia.org/wiki/Tests_of_general_relativity",
"https://en.wikipedia.org/wiki/Test_(wrestler)"
]
]
Just using the core .Net libraries i.e. no NewtsonSoft libraries etc.
I am working on a Windows Phone 8.1 application involving location. I am receiving Json data from my API. My API returns data that looks like:
[{
"country": "India",
"city": "Mall Road, Gurgaon",
"area": "Haryana",
"PLZ": "122002",
"street": "",
"house_no": "",
"POI": "",
"type": "17",
"phone": "",
"lng": 77.08972334861755,
"lat": 28.47930118040612,
"formatted_address": "Mall Road, Gurgaon 122002, Haryana, India"
},
{
"country": "India",
"city": "Mall Road, Kanpur",
"area": "Uttar Pradesh",
"PLZ": "208004",
"street": "",
"house_no": "",
"POI": "",
"type": "17",
"phone": "",
"lng": 80.35783410072327,
"lat": 26.46026740300029,
"formatted_address": "Mall Road, Kanpur 208004, Uttar Pradesh, India"
},
{
"country": "India",
"city": "Mall Road Area, Amritsar",
"area": "Punjab",
"PLZ": "143001",
"street": "",
"house_no": "",
"POI": "",
"type": "17",
"phone": "",
"lng": 74.87286686897278,
"lat": 31.64115178002094,
"formatted_address": "Mall Road Area, Amritsar 143001, Punjab, India"
},
{
"country": "India",
"city": "Vasant Kunj (Mall Road Kishan Garh), New Delhi",
"area": "Delhi",
"PLZ": "110070",
"street": "",
"house_no": "",
"POI": "",
"type": "18",
"phone": "",
"lng": 77.1434211730957,
"lat": 28.51363217008815,
"formatted_address": "Vasant Kunj (Mall Road Kishan Garh), New Delhi 110070, Delhi, India"
}]
I am deserializing my Json data and putting it into a class named LocationData. When I run my code, it gives me an error:
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path
Where am I going wrong? Here is my code:
private async void GetAPIData()
{
string _serviceUrl = "https://api.myweblinkapiprovider/v2&q=" + UserRequestedLocation;
HttpClient client = new HttpClient();
HttpResponseMessage responce = await client.GetAsync(new Uri(_serviceUrl));
if (responce.Content != null)
{
var respArray = JObject.Parse(await responce.Content.ReadAsStringAsync());
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.MissingMemberHandling = MissingMemberHandling.Ignore;
var rcvdData = JsonConvert.DeserializeObject<LocationData>(respArray.ToString(), settings);
UpdateMapData(rcvdData);
UpdateTextData(rcvdData);
}
}
I also tried to use a JArray. My code is as below:
private async void GetAPIData()
{
string _serviceUrl = "https://api.myweblinkprovider.com/v3?fun=geocode&lic_key=MyKey" + UserRequestedLocation;
HttpClient client = new HttpClient();
HttpResponseMessage responce = await client.GetAsync(new Uri(_serviceUrl));
JArray arr = JArray.Parse(await responce.Content.ReadAsStringAsync());
foreach (JObject obj in arr.Children<JObject>())
{
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.MissingMemberHandling = MissingMemberHandling.Ignore;
var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr.ToString(), settings);
UpdateMapData(rcvdData);
UpdateTextData(rcvdData);
}
}
It also gives me an error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MMI_SpeechRecog.Model.LocationData' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:
[A] JObject isn't the elementary base type of everything in JSON.net, but JToken is. So even though you could say,
object i = new int[0];
in C#, you can't say,
JObject i = JObject.Parse("[0, 0, 0]");
in JSON.net.
What you want is JArray.Parse, which will accept the array you're passing it (denoted by the opening [ in your API response). This is what the "StartArray" in the error message is telling you.
As for what happened when you used JArray, you're using arr instead of obj:
var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);
Swap that, and I believe it should work.
Although I'd be tempted to deserialize arr directly as an IEnumerable<LocationData>, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.
In this case that you know that you have all items in the first place on array you can parse the string to JArray and then parse the first item using JObject.Parse
var jsonArrayString = #"
[
{
""country"": ""India"",
""city"": ""Mall Road, Gurgaon"",
},
{
""country"": ""India"",
""city"": ""Mall Road, Kanpur"",
}
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());
I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.
jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
I was then able to use the JObject.Parse(jsonResult) and everything worked.
The following worked for me to convert a list of objects to json.
using Newtonsoft.Json;
static void Main(string[] args)
{
List<eventResponse> o = new List<eventResponse>()
{
new eventResponse { acknowledge = "test" } ,
new eventResponse { acknowledge = "test 2" }
};
var json = JsonConvert.SerializeObject(o);
JArray jo = JArray.Parse(json);
Console.WriteLine(jo);
}
public class eventResponse
{
public string acknowledge { get; set; }
}
A delayed answer but if you have access to the API you can work on the javascript object to make it as JSon. Something like
var jsonAddresses = { "addresses":
[
{
"country": "India",
"city": "Mall Road, Gurgaon",
},
{
"country": "India",
"city": "Mall Road, Kanpur",
}
]};
Then in C#
JObject Addjson = JObject.Parse(model.YourAddressesSampleJSONStr);
I have a Json String that I get from a web service; it has a list of collections, each collection represents an object, for example:
[ // Root List
[ // First Collection : Team Object
{
"id": 1,
"team_name": "Equipe Saidi",
"is_active": true,
"last_localisation_date": "2015-05-06T13:33:15+02:00"
},
{
"id": 3,
"team_name": "Equipe Kamal",
"is_active": true,
"last_localisation_date": "2015-05-06T09:22:15+02:00"
}
],
[// Second Collection : user Object
{
"id": 1,
"login": "khalil",
"mobile_password": "####",
"first_name": "Abdelali",
"last_name": "KHALIL",
"email": "KHALIL#gmail.com",
"role": "DR",
"is_active": true,
"charge": false
},
{
"id": 2,
"login": "ilhami",
"mobile_password": "####",
"first_name": "Abdellah",
"last_name": "ILHAMI",
"email": "ILHAMI#gmail.com",
"role": "DR",
"is_active": true,
"charge": false
}
]
]
My actual code (not working of course ):
public async Task TeamsAndMobileUsers()
{
string data = "";
IList<User> MobileUsersList = new List<User>();
IList<Team> TeamsList = new List<Team>();
try
{
data = await GetResponse(PATH + TEAMS_USERS_URL);
TeamsList = JsonConvert.DeserializeObject<List<Team>>(data);
MobileUsersList = JsonConvert.DeserializeObject<List<User>>(data);
// Inserting
await SetAchievedActions(TeamsList);
}
catch (Exception e) {
_errors.Add(e.Message);
}
}
I use Json.net and C#. I can't find a solution, I've read that I should use JsonReader and set its SupportMultipleContent property to true but I don't know how to implement that solution.
As #YeldarKurmangaliyev already said, your json has two different objects, I think you can do something like this:
var j = JArray.Parse(data);
TeamsList = JsonConvert.DeserializeObject<List<Team>>(j[1].ToString());
MobileUsersList = JsonConvert.DeserializeObject<List<User>>(j[2].ToString());
have you tried http://json2csharp.com/ to generate contract classes for that json? also, first and last parenthesis gives a not valid JSON
You need to create 4 classes
1st class TeamObject : Variable(id,team_name,is_active,last_localisation_date)
2nd class UserObject : Variable (id, login,mobile_password,first_name, last_name , email, role,is_active,charge)
3rd class RootList: Variable ( arraylist<TeamObject> obj, arraylist<UserObject > obj2)
4th class RootClass : Variable(arraylist<RootList> obj)
Gson gson=new Gson();
RootClass dtomodel = gson.fromJson(data , RootClass .class);
This parsing done using Gson Library
I am planning to write a simple SugarCrm .Net client.
Could anyone give me a pointer to a .Net wrapper/library for the SugarCrm REST api?
//lasse
Realize this is old, but in case anyone stumbles across this looking for a .NET wrapper for newer version of the web service (SugarCRM > 6.7), here is a wrapper I am currently building https://github.com/dlively1/SugarSharp
There is a wrapper that uses SOAP called CandyWrapper, which is a bit old but could help you with a starting point on building your own.
http://developers.sugarcrm.com/wordpress/2011/08/10/web-services-in-your-own-language-part-6-candywrapper-for-net/
I also realize this is old, but for SugarCRM CE 6.x I created SugarRestSharp. The sample I give below is in json, but the request would be in C# models. This implements get_entry_list SugarCrm Rest API method.
Passing request to RestSharp:
dynamic data = new
{
session = sessionId,
module_name = moduleName,
query = queryString,
order_by = string.Empty,
offset = 0,
select_fields = selectFields,
link_name_to_fields_array = string.Empty,
max_results = maxCountResult,
deleted = 0,
favorites = false
};
var client = new RestClient(url);
var request = new RestRequest(string.Empty, Method.POST);
string jsonData = JsonConvert.SerializeObject(data);
request.AddParameter("method", "get_entry_list");
request.AddParameter("input_type", "json");
request.AddParameter("response_type", "json");
request.AddParameter("rest_data", jsonData);
var response = client.Execute(request);
Request in json
{
"session": "olgg6hf5sqi6hk9u3tgpafbn66",
"module_name": "Accounts",
"query": "",
"order_by": "",
"offset": 0,
"select_fields": [
"name",
"industry",
"website",
"shipping_address_city",
"id"
],
"link_name_to_fields_array": "",
"max_results": 10,
"deleted": 0,
"favorites": false
}
Response in json
{
"result_count": 10,
"total_count": "58",
"next_offset": 10,
"entry_list": [
{
"id": "1e0eec64-8cc6-58ff-57f1-58533731b145",
"module_name": "Accounts",
"name_value_list": {
"name": {
"name": "name",
"value": "New SugarRestSharp Acccount 1 10397"
},
"industry": {
"name": "industry",
"value": "Manufacturing"
},
"website": {
"name": "website",
"value": "www.sugarrestsharp1.com"
},
"shipping_address_city": {
"name": "shipping_address_city",
"value": "Los Angeles"
},
"id": {
"name": "id",
"value": "1e0eec64-8cc6-58ff-57f1-58533731b145"
}
}
},
......... (other 9 items truncated)
],
"relationship_list": [
]
}
For more implementation and wiki check SugarRestSharp: https://github.com/mattkol/SugarRestSharp