How to use JSON in sketchware


WHAT IS JSON

JSON (JavaScript object notation) is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application. 

Types of data

  1. Maps

    Maps are key:value pairs enclosed in curly brackets( { } ) and separated by commas after each key value pairs. 

    In Sketchware you can convert a map to JSON by the following way:


    Then you can use this block to convert to json



    The result of the above example will be:
    JSON:
    {
    "key1" : "value1",
    "key2" : "value2",
    "key3" : "value3"
    }
    As you can see the map first starts with the curly bracket then comes the key:value pairs
    All keys are enclosed in double quotes and values are enclosed in double quotes if it is a string. And it ends with a closing curly bracket.



  2. Array

    In Sketchware point of view array is just a list. Arrays are enclosed in square brackets. ([ ]). Arrays can store data including string, maps or even another array. An array inside an array is called 'nested array'. 
    The type of array used widely for APIs is maplist. You can generate a maplist using the following blocks

    This will generate the following json

    JSON:
    [{
    "key1" : "value1",
    "key2" : "value2",
    "key3" : "value3"
    },
    {
    "key1" : "value1",
    "key2" : "value2",
    "key3" : "value3"
    },
    {
    "key1" : "value1",
    "key2" : "value2",
    "key3" : "value3"
    }]

    you can use this block to convert to json string

  HOW TO USE NESTED JSON

You can store an array inside another array or map. Similarly you can also store a map inside another map or array.

for example:
JSON:{
  "json_string": [
    {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
    },
    {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
    }
  ]
}


  • create a string variable (This is for storing the json
  • also create a maplist 

now, use the following code to set the get the nested array as json to the created string variable
 <string> = (new Gson()).toJson(train.get("<key>"), new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());

here, replace <string> with the string variable you created and <key> with the key in your json that you want to access

Similarly you can access map using the following codes
string = (new Gson()).toJson(var_map.get("key"),new TypeToken<HashMap<String, Object>>() {}>.getType());


No comments:

Powered by Blogger.