0

I am trying to port a piece of Code from Java to C# and I am stuck in JSon parsing. Have a look at the following Java Code

        mJsonObject = new JSONObject(str);
        Iterator<String> keys=mJsonObject.keys();
        while(keys.hasNext()){

            String key=keys.next();
            String value=mJsonObject.getString(key);

            mAdData.add(new AdData(key, new JSONObject(value)));


        }

I had a string which has verified Json format and I passed it to JSONObject and every thing was finely working in Java, but now in C# Unity I am not able to port it successful. I am using LitJson to perform this task and I have no idea how this works. I am badly stuck please help. Thanks

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Jawad Amjad
  • 2,532
  • 2
  • 29
  • 59
  • Do you get an exception, what is the issue, please provide some detail – Mrinal Kamboj Dec 22 '14 at 10:40
  • The above mentioned code is Java code I need its conversion to C#. I have tried some but failed Here is the code JsonData mJsonObject = JsonMapper.ToObject (dataObj); IEnumerator keys = (IEnumerator)mJsonObject.Keys; Error on second line is System.InvalidCastException: Cannot cast from source type to destination type. – Jawad Amjad Dec 22 '14 at 10:42

1 Answers1

1

The keys method of the JSONObject class returns an ICollection<string>. You can iterate an ICollection like this. So I would change your while loop into a foreach, like this:

foreach (string key in keys) {
    //whatever
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • Thanks a lot its working. Now the next step is to get the value against the key. How can I do that? Please let me know. – Jawad Amjad Dec 22 '14 at 13:34
  • Please, take a look here: http://stackoverflow.com/questions/19974763/get-values-and-keys-in-json-object-using-json-net-c-sharp. If an answer solves your problem, then please consider accepting it to help future visitors having the same kind of problem. – Lajos Arpad Dec 22 '14 at 13:52
  • the above method does not work for me unfortunately. If my problem is solved I will definitely accept the answer. – Jawad Amjad Dec 23 '14 at 06:28