0

I'm trying to parse this string:

[{"busses":[{"bus":1,"time":"2016-10-11 04:56:01","lat":"30.5198498","lon":"-90.47052981","acc":"6.0\n"},{"bus":2,"time":"2016-10-11 11:37:55","lat":"30.51764384","lon":"-90.47189947","acc":"3.0\n"},{"bus":3,"time":"2016-10-05 03:52:11","lat":"30.51982784","lon":"-90.47063428","acc":"8.0\n"},{"bus":4,"time":"2016-10-11 11:37:56","lat":"30.51998849","lon":"-90.47060976","acc":"3.0\n"}]}]

Here is my old code...:

public class Bus
{
    public string busNum { get; set; }
    public string busTime { get; set; }
    public string busLat { get; set; }
    public string busLon { get; set; }
    public string busAcc { get; set; }
}

public class Busses
{
    public List<Bus> busses { get; set; }
}

public class TestCoordinate : MonoBehaviour
{
    private float nextActionTime = 0.0f;
    private float period = 5.0f;
    void Start()
    {

    }
    void Update()
    {
        if (Time.time > nextActionTime)
        {
            nextActionTime = Time.time + period;
            StartCoroutine("GetCoordinatesUpdate");
        }

    }

    IEnumerator GetCoordinatesUpdate()
    {
        WWW www = new WWW("Myurl.com");
        yield return www;
        string cleanurl = www.text.Replace("(", "").Replace(")", "");
        string finalurl = "[{\"busses\":" + cleanurl + "}]";
        Debug.Log(finalurl);
        Busses busses = JsonMapper.ToObject<Busses>(finalurl);
    }
}

EDIT: After referencing the link: Serialize and Deserialize Json and Json Array in Unity, I've changed my code to this, please see my error below:

    public class Bus
{
    public string bus;
    public string Time;
    public string Lat;
    public string Lon;
    public string Acc;
}

public static class JsonHelper
{
    public static T[] FromJson<T>(string json)
    {
        Wrapper<T> wrapper = UnityEngine.JsonUtility.FromJson<Wrapper<T>>(json);
        return wrapper.Items;
    }

    public static string ToJson<T>(T[] array)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return UnityEngine.JsonUtility.ToJson(wrapper);
    }

    [Serializable]
    private class Wrapper<T>
    {
        public T[] Items;
    }
}

public class TestCoordinate : MonoBehaviour
{
    private float nextActionTime = 0.0f;
    private float period = 5.0f;
    public Bus[] busInstance;
    public string lat;
    void Start()
    {

    }
    void Update()
    {
        if (Time.time > nextActionTime)
        {
            nextActionTime = Time.time + period;
            StartCoroutine("GetCoordinatesUpdate");
        }

    }

    IEnumerator GetCoordinatesUpdate()
    {
        //string url = "http://gdata.selu.edu/traxx/allpositions2.php";
        WWW www = new WWW("http://gdata.selu.edu/traxx/allpositions2.php");
        yield return www;
        string cleanurl = www.text.Replace("(", "").Replace(")", "").Replace("\n","");
        string finalurl = "{\"busses\":" + cleanurl + "}";
        Debug.Log(finalurl);  
        busInstance = JsonHelper.FromJson<Bus>(finalurl);
        lat = busInstance[0].Lat;
        Debug.Log(lat);        
    }
}

Note:However now I'm getting an error saying "NullReferenceException: Object reference not set to an instance of an object" when trying to display the lat. I also tried busInstance.Length, and I receive the same error. What's wrong, am I missing something simple that I'm not seeing?

I'm trying to get the 4 busses into a list using the JsonMapper.ToObject from LitJson.

I've referenced this post: how to parse json array using Litjson? ...And that post is what I've built this on. However, I'm getting an error saying "Type Busses can't act as an array."

You will see that I've concatenated "[{busses:" to the string in order to have it resemble the post I referenced.

Note: I'm using LitJson and Unity.

Community
  • 1
  • 1
  • What are you trying to do in `GetCoordinatesUpdate` ? What is the use of those string operations – L.B Oct 11 '16 at 17:04
  • I'm retrieving the Json string from a webpage, then modifying the string to fit the certain conditions. – cbender165 Oct 11 '16 at 17:06
  • Don't modify it, use it as it is.... It is a valid json... – L.B Oct 11 '16 at 17:12
  • This is the string before its modded: "([{"bus":1,"time":"2016-10-11 04:56:01","lat":"30.5198498","lon":"-90.47052981","acc":"6.0\n"},{"bus":2,"time":"2016-10-11 12:15:57","lat":"30.51261627","lon":"-90.46495531","acc":"3.0\n"},{"bus":3,"time":"2016-10-05 03:52:11","lat":"30.51982784","lon":"-90.47063428","acc":"8.0\n"},{"bus":4,"time":"2016-10-11 12:15:56","lat":"30.52158994","lon":"-90.47426994","acc":"3.0\n"}])" So, I wanted to mod it to get rid of parenthesis, and to add the leading "busses". – cbender165 Oct 11 '16 at 17:16
  • Possible duplicate of [Deserialization of JSON using MiniJSON in Unity C#](http://stackoverflow.com/questions/36239705/deserialization-of-json-using-minijson-in-unity-c-sharp) – Programmer Oct 11 '16 at 17:23
  • I've edited my post, I've tried the changes, however now I'm getting a "Object reference not set to an instance of an object" error. – cbender165 Oct 11 '16 at 20:37

1 Answers1

1

Yes, you are missing something simple. In the post you referenced, they are manipulating the JSON to surround it with { "Items": and }. This extra bit of JSON is then used by the JsonHelper.Wapper<T> class to extract the JSON array. The Wrapper class depends on the name of that outer property being "Items", but you have changed it to "busses". As a result, the deserializer is not able to populate the Items array, which remains null, and is then ultimately assigned to your busInstance variable. Since busInstance is null you will get a NullReferenceException when you try to access busInstance[0].Lat.

So, it seems the quick fix is to change this line:

string finalurl = "{\"busses\":" + cleanurl + "}";

To this:

string finalurl = "{\"Items\":" + cleanurl + "}";

I have to admit I'm not a fan of this whole approach of manipulating the JSON, because it feels really hacky to me. Apparently, the whole purpose of this is to get around a limitation in the Unity serializer in which it does not support top-level arrays. A better approach, in my opinion, is not to attempt to doctor the JSON at all (except for stripping off the outer parentheses, which is still an unfortunate necessity in this case), and instead just deserialize the JSON directly into your Bus array. You can do this easily with LitJSON, which you originally referenced in your "old" code:

busInstance = JsonMapper.ToObject<Bus[]>(cleanurl);

As an aside, I would recommend renaming your busInstance variable to busArray since it is an array and not a single instance of Bus. Keeping variable names accurate is important for others to be able to understand your code.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300