(Updated 12/1/11) It's the season for sharing.
Attached is a handy script for encoding and decoding JSON data. This could be used as a way to pack arrays and dictionaries into PlayerPrefs, or a way to interact with web services.
It's a small modification of a script I found online:
http://techblog.procurios.nl/k/618/n...-for-JSON.html
I modified it so that it would run in Unity iPhone without complaining or throwing exceptions.
It can encode any basic type (int, string, float, etc.) and arrays, ArrayLists, and hashtables. Note: When you decode an array you always get an ArrayList back.
There are a couple areas that I haven't tested throughly:
* I haven't tried encoding and decoding Unicode text (above the normal ASCII range)
* I haven't tried encoding and decoding numbers in a locale that uses . as the thousands seperator (1.234,56). I also haven't tried encoding numbers in one locale and decoding in another.
Here's an example that gets tweets mentioning Unity3d:
Code:
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using MiniJSON; } IEnumerator GetTwitterUpdate() { float elapsedTime = 0.0f; if (elapsedTime >= 10.0f) break; yield return null; } yield break; } string response = www.text; IDictionary search = (IDictionary) Json.Deserialize(response); IList tweets = (IList) search["results"]; foreach (IDictionary tweet in tweets) { } } }
GitHub Gist: MiniJSON.cs
For more complicated JSON serializing and deserializing, I highly recommend using JsonFX.
JsonFX for Unity
Edit: Updated and optimized this script to use generics and StringBuilders throughout. I've tested it with a ~32k JSON file, and it was able to serialize and deserialize it without issue. Added an MIT license header.

Reply With Quote
