2

I'm a total noob regarding JSON, never worked with it before and I just can't figure it out. I've tried many things but I just jump around from error to error. I hope someone can help me.

so this is a sample of my JSON file, I read this file from a website.

[{"ID":60034,"Datetime":1519029071,"Module":"Krol 42","Latitude":51.8423083333333,"Longitude":4.57711,"Speed":0.59264},{"ID":58961,"Datetime":1519025476,"Module":"Krol 42","Latitude":51.8422666666667,"Longitude":4.576865,"Speed":0.59264}]

and this is the my script:

[Serializable]
public class Item
{
    public int ID;
    public int Datetime;
    public string Module;
    public float Latitude;
    public float Longitude;
    public float Speed;
}

public class JsonHelper
{
    public static T[] getJsonArray<T>(string json)
    {
        string newJson = "{ \"array\": " + json + "}";
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>> (newJson);
        return wrapper.array;
    }

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

IEnumerator Start()
{
    string url = "http://tnt.ssedemo.eu/TrackAndTraceStrukton.aspx";
    WWW www = new WWW(url);

    yield return www;

    if (www.error == null)
    {
        string jsonString = www.text;
        Item[] item = JsonHelper.getJsonArray<Item> (jsonString);
        Debug.Log (item[0].ID);
    }
    else
    {
        Debug.Log("ERROR: " + www.error);
    }        
}

and the error I'm getting now atm is:

ArgumentException: JSON parse error: Missing a comma or '}' after an object member.

I hope someone can help me, I would appreciate it a lot, thanks in advance.

[EDIT]

SOLUTION

    [Serializable]
public class Item
{
    public int ID;
    public int Datetime;
    public string Module;
    public float Latitude;
    public float Longitude;
    public float Speed;
}

public class JsonHelper
{
    public static T[] getJsonArray<T>(string json)
    {
        string newJson = "{ \"array\": " + json + "}";
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>> (newJson);
        return wrapper.array;
    }

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

IEnumerator Start()
{
    string url = "http://tnt.ssedemo.eu/TrackAndTraceStrukton.aspx";
    WWW www = new WWW(url);

    yield return www;

    if (www.error == null){
        string jsonString = www.text;
        int index = jsonString.LastIndexOf("]");
        if (index > 0){ 
            jsonString = jsonString.Substring(0, index + 1);
        }
        Item[] item = JsonHelper.getJsonArray<Item> (jsonString);
        foreach(Item krol in item){
            Transform ride = Instantiate(prefab, new Vector3(krol.Longitude * 10f, 2f, krol.Latitude * 10f), Quaternion.identity) as Transform;
        }
    } else {
        Debug.Log("ERROR: " + www.error);
    }        
}
Bosanac95
  • 75
  • 12
  • Where you getting the error? – Ramesh Rajendran Feb 19 '18 at 10:35
  • @RameshRajendran just as soon as I start the scene, the script is active in the hierarchy – Bosanac95 Feb 19 '18 at 10:36
  • 1
    What is the exact content of `jsonString` during debugging? – Rafalon Feb 19 '18 at 10:38
  • @Rafalon Yes, when I debug jsonstring I get the json data no problem in my console from the site, and it looks just like the sample – Bosanac95 Feb 19 '18 at 10:41
  • Then maybe you should remove opening and closing square brackets? – Rafalon Feb 19 '18 at 10:43
  • @Rafalon how would I do that? – Bosanac95 Feb 19 '18 at 10:47
  • Well you could use `.Replace('[','').Replace(']','')` or `.Substring(1,jsonString.Length-2)`. It depends wether those square brackets are there regardless the source – Rafalon Feb 19 '18 at 10:52
  • @Rafalon I used Replace() and now I get "ArgumentException: JSON parse error: Missing a name for object member." :( – Bosanac95 Feb 19 '18 at 10:56
  • Try with `.Replace('[','{').Replace(']','}')` instead – Rafalon Feb 19 '18 at 10:57
  • @Rafalon nope, same error as before :/ – Bosanac95 Feb 19 '18 at 10:59
  • 1
    After some investigation, I am on the wrong way, those brackets are normal. Have you checked [this link](https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity/36244111#36244111) (the **2. MULTIPLE DATA(ARRAY JSON)** part) ? – Rafalon Feb 19 '18 at 11:03
  • Please don't ask the-same question again. I've marked your json question as duplicate before. Why ask again when you could just reply to me in your other question. Read the duplicate.1.Like @Rafalon said read **2. MULTIPLE DATA(ARRAY JSON**. 2.Once you get the `JsonHelper` wrapper from there,read **If this is a Json array from the server and you did not create it by hand:** from there too. It shows that you have to fix your json to work with that wrapper since the json was not created with the `JsonHelper` wrapper. A `fixJson` function is given to you and example on how to use it is also there – Programmer Feb 19 '18 at 12:19
  • @Programmer please unmark the question as duplicate, since the problem is not in the JSon retrieval, but in the retrieved `www.text`. I'll write the answer as soon as you unmark it. – Galandil Feb 19 '18 at 12:39
  • @Galandil Unmark a duplicate as a duplicate? There is only one problem here which is "Json Array" and th duplicate show how to fix that. I could just copy that part json array part and put it as an answer here if I wanted to but it only makes finding json questions harder or even closing duplicates. – Programmer Feb 19 '18 at 12:46
  • @Programmer I meant unmark it in order to be able to give an answer. As I said, the problem **IS NOT** in the JSon wrapper, but in how the text is retrieved from the URL, since there's additional text after the `]` of the JSon text. – Galandil Feb 19 '18 at 12:49
  • @Programmer my apologies for asking again and not asking you in the previous question. I have taken a look at your answer in the other question and I have done so in my code as you have explained there, the helper class and the fix function, but I still get the same error "Missing a comma or '}' after an object member." – Bosanac95 Feb 19 '18 at 12:49
  • @Bosanac95 indeed, as soon as I'm able to post an answer I'll explain how to fix it. :) – Galandil Feb 19 '18 at 12:50
  • @Galandil Thank you :) – Bosanac95 Feb 19 '18 at 12:52
  • 1
    @Bosanac95 Can you add EDIT to your question with your updated code that's not working after you looked at the duplicate. Also post a copy of `JsonHelper` you are using. – Programmer Feb 19 '18 at 12:54
  • @Programmer why do you insist on keeping the question closed as a duplicate since I already told you that it's not a duplicate and I already found a solution, which has nothing to do with the linked answer? – Galandil Feb 19 '18 at 12:57
  • 1
    @Galandil Don't worry I will if I see what OP has. I have opened duplicates in the past and it runs out it was a duplicate because OP wasn't doing it right. Duplicate should be opened if you see that OP has implemented what's in the duplicate. This is not true so far – Programmer Feb 19 '18 at 13:04
  • @Programmer And I'm telling you that his initial code works fine without the need to copy/paste the code from the duplicate, the problem is elsewhere. Why do you insist on not believing me? – Galandil Feb 19 '18 at 13:06
  • @Bosanac95 **One** of problem is that the json you posted in your question is not the actual json from the server you are requesting. You posted wrong json making every frame think that your json is valid. Your json is not valid and this is mentioned the duplicate. See **4.TROUBLESHOOTING JsonUtility:** from the duplicate which mentions you will get error if your json is not valid. and show you how to verify this. Your server is returning a whole html page after returning the json and you need to fix that. – Programmer Feb 19 '18 at 13:09
  • See what you server is returning [here](https://codeshare.io/a3x67B). Please post your real json next time. @Galandil This has nothing to do with extra ']'. – Programmer Feb 19 '18 at 13:11
  • @Bosanac95 Because your json from server is really huge, Unity will truncate it in order to display it in the Console tab. If this happens to you again in the future, use `GUIUtility.systemCopyBuffer` to force Unity to obtain the whole json to post in your SO question. You can obtain all of them by doing `GUIUtility.systemCopyBuffer = jsonString` which will put it in the memory then paste it in a notepad to see for yourself. Fix your server and make it to stop returning html after the json. Even after you fix your json, you must also follow the duplicate to make it work. – Programmer Feb 19 '18 at 13:15
  • @Programmer ok, I'm on the verge on reporting your behaviour to the staff. You haven't even read what I said, I've not said "extra ]" but "additional text AFTER the ]", and what you linked now is exactly what I found out more than 20 minutes ago, and with a ready solution to his problem. But apparently your ego got in the way. – Galandil Feb 19 '18 at 13:16
  • @Bosanac95 I don't think the question will ever be re-opened, if it happens I'll elaborate on a proper answer. In the meantime, to solve your problem, in your original code just add these lines after the declaration of `string jsonString = www.text;` : `int index = jsonString.LastIndexOf("]"); if (index > 0) { jsonString = jsonString.Substring(0, index + 1); }` – Galandil Feb 19 '18 at 13:35
  • @Galandil shouldn't `LastIndexOf` be `FirstIndexOf`? What if the html contains a `]` in it? – Rafalon Feb 19 '18 at 13:42
  • 1
    @Galandil Sure, [here](https://stackoverflow.com/company/contact) is their contact info. 1.With the original code in the question, OP's problem wouldn't be fixed even if the extra characters are removed because the json array de-serialization is plain wrong. 2.Your solution would have said that there is extra text in the json which means that the json is not invalid. This is mentioned in the duplicate in the **troubleshooting** section and a link is even provided there to verify if the json is valid or not. The fix should be done on the server not client as that can go wrong. – Programmer Feb 19 '18 at 13:43
  • @Galandil Thank you so much!! it works now! – Bosanac95 Feb 19 '18 at 13:44
  • @Programmer 1. With my fix the problem is **SOLVED**, I tested it myself. And apparently it worked even for Bosanac95. 2. It may well be that he isn't the one who creates the JSON, so saying that "it must be fixed on the server side" is not a solution by itself. – Galandil Feb 19 '18 at 13:50
  • @Galandil that is very true, the server is not mine, its from a company, not an option for me to alter the json – Bosanac95 Feb 19 '18 at 13:52
  • @Rafalon The additional HTML text is appended at the end of the JSON text, so he needs to remove all the text after the `]`. Your question is valid though, he could search for `}]` as the last index, or some other patterns that could be thought of, I didn't research this JSON in depth. – Galandil Feb 19 '18 at 13:53
  • @Bosanac95 thought so. :) – Galandil Feb 19 '18 at 13:53
  • @Galandil but again thank you so much for your solution, I am very grateful, finally I can continue haha :) – Bosanac95 Feb 19 '18 at 13:53

0 Answers0