我正在尝试解析这个字符串:
[{"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"}]}]
这是我的旧代码...:
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);
}
}
编辑:引用链接后:Serialize and Deserialize Json and Json Array in Unity,我已将代码更改为此,请参阅下面的错误:
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);
}
}
注意:但是现在我在尝试显示 lat. 我也试过 busInstance.Length,我收到了同样的错误。怎么了,我错过了一些我没有看到的简单的东西吗?
我正在尝试使用 LitJson 的 JsonMapper.ToObject 将 4 条总线放入列表中。
我引用了这篇文章:如何使用 Litjson 解析 json 数组? ...而那篇文章就是我建立的。但是,我收到一条错误消息,提示“类型总线不能充当数组”。
您会看到我已将“[{busses:” 连接到字符串,以使其类似于我引用的帖子。
注意:我使用的是 LitJson 和 Unity。