how to parse a json feed
I am pulling a JSON feed from a rest api into my gear vr app. I'm really new to unity and am having trouble figuring out how to access the data. My code is below:
Sample of JSON:
[
{
"id": "2",
"list_title": "Half Asleep",
"description": "Google finds."
},
{
"id": "1",
"list_title": "My list of favorites",
"description": "Here is some stuff I find quite cool"
}
]
My attempt at a container class for the JSON:
using UnityEngine;
[System.Serializable]
public class CuratedList
{
public string id;
public int list_title;
public float description;
public static CuratedList CreateFromJSON(string jsonString)
{
return JsonUtility.FromJson<PlayerInfo>(jsonString);
}
}
And my FeedManager class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SimpleJSON;
public class FeedManager : MonoBehaviour {
// Use this for initialization
IEnumerator Start () {
WWW www = new WWW("http://youngwolf0.com/rest/views/virtual_reality_gallery");
yield return www;
Processjson(www.data);
}
// Update is called once per frame
void Update () {
}
private void Processjson(string jsonString)
{
var N = JSON.Parse(jsonString);
var data = N.AsArray;
}
}
In the debugger I can see that my feed is being pulled in, all I need to do is get the data into a format I can loop through and access the values. I'm using this code as a basis for a more complex feed later on. I gather that I need the container class but I'm not sure how to plumb this all together.
Answer by DFT-Games · May 29, 2017 at 11:50 PM
Hi @youngwolf0 ,
The JSON utilities that come with Unity are designed to deal with serializing Unity objects, not really useful for JSON data unrelated to Unity. There is a free asset that does a decent job on the Asset Store, called JSONObject. Personally I like better NewtonSoft, so my personal advice is to buy JSON .NET For Unity, it's my preferred asset for all my JSON needs in Unity.
Thanks for the pointer, I'm not going to be making money for this for a while so free is good enough for now, I'll keep a note of the .net option for the future though :)
It makes sense indeed :) The free asset is not bad, just do read the docs because is a tad convoluted if you are used to standard JSON parsing.
Your answer
Follow this Question
Related Questions
SHA512 JS -> C# 0 Answers
Deserialize Json array with mixed types 0 Answers
Can WWW return a JOSN string? 0 Answers
Refresh Chat room messages 1 Answer