Saturday, January 3, 2015

Introduction to Json

Introduction to Json


What Json Object looks like?

eg: {"apple","cherry","grapes"}


What Json Array looks like?

eg: {"fruits":[{"apple","grapes"},{"cherry","banana"},{"pineapple","orange"}],"vegetable":[{"carrot","leeks"},{pumpkin,tomato}]}


What Json String looks like? 

eg: '{"apple","cherry","grapes"}'


Using JSON with Different Platforms

Since JSON is so popular, there are parsers (tools and libraries that decode one programming language so that another can understand it) and generators (tools and libraries that do the opposite; encode one programming language into another) available for most programming languages.I'll highlight a few...

For .NET:

#using System.Json; 
decoded = JsonValue.Parse(jsonString);  //may be a JsonPrimitive, JsonArray, or JsonObject, depending on the JSON passed


For JavaScript (including HTML 5 apps):

You could just pass the JSON string to eval() in JavaScript, but this is a terrible security risk. Most modern browsers support a function JSON.parse(), which will parse a JSON string into JavaScript objects, and JSON.stringify(), which will turn a JavaScript object or array into a JSON string.

For Java (example):

public class test
{
    public static void main(String str[])
    {
        String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject newJSON = jsonObject.getJSONObject("stat");
        System.out.println(newJSON.toString());
        jsonObject = new JSONObject(newJSON.toString());
        System.out.println(jsonObject.getString("rcv"));
       System.out.println(jsonObject.getJSONArray("argv"));
    }
}