Gson

Extracting keys and values from json string using Gson


package com.logztechstuff.json.gson;

import java.util.Iterator;
import java.util.Map;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class GsonParser {
public static void main(String[] args) {

        String json = "{ name : \"foo\", company : \"bar\", ph : [9912345667, 7744554287]}";
        JsonParser parser = new JsonParser();
        JsonObject jsonObject = (JsonObject) parser.parse(json);
        //Check the parsed string is json or not
        if(jsonObject.isJsonObject()) {
            System.out.println("Yes it is json object");
            //Extracting keys and values from json
            for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
                System.out.println("Key :: " + entry.getKey());
                System.out.println("Value :: " + entry.getValue());
            }

            //Checking extracted json is a JsonArray or not
            JsonArray jsonArray = jsonObject.get("ph").isJsonArray() ? jsonObject.get("ph").getAsJsonArray() : null;

            //Checking jsonarray is not null, printing all values from array if it is not null
            if (jsonArray != null) {
                Iterator<JsonElement> itr = jsonArray.iterator();
                while (itr.hasNext()) {
                    System.out.println("Number :: " + itr.next());
                }
            }
        }
}
}
Scripts

Ping Success or Failure

Shell script to check whether ping is success for given IP.


IP=x.x.x.x
PING_COUNT=3
ping_result=$(ping $IP -c$PING_COUNT | grep 'received' | awk -F',' '{print $2}' | awk '{print $1}')
if [ $ping_result -eq 0 ] ; then
    ping_msg="Ping is failed to $IP"
else
    ping_msg="Ping is successful to $IP"
fi