Example usage for com.google.gson JsonElement getAsInt

List of usage examples for com.google.gson JsonElement getAsInt

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsInt.

Prototype

public int getAsInt() 

Source Link

Document

convenience method to get this element as a primitive integer value.

Usage

From source file:com.tsc9526.monalisa.tools.json.MelpJson.java

License:Open Source License

public static int getInt(JsonObject json, String name, int defaultValue) {
    JsonElement e = json.get(name);
    if (e == null || e.isJsonNull()) {
        return defaultValue;
    } else {//from ww w. j  ava  2s  . com
        return e.getAsInt();
    }
}

From source file:com.unovo.frame.utils.gson.deserializer.IntegerJsonDeserializer.java

License:Open Source License

@Override
public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    try {/*from  ww  w  .  j  av a2 s.co m*/
        return json.getAsInt();
    } catch (Exception e) {
        Logger.i("IntegerJsonDeserializer-deserialize-error:" + (json != null ? json.toString() : ""));
        return 0;
    }
}

From source file:com.uwetrottmann.tmdb.TmdbHelper.java

License:Apache License

/**
 * Create a {@link com.google.gson.GsonBuilder} and register all of the custom types needed in
 * order to properly deserialize complex TMDb-specific types.
 *
 * @return Assembled GSON builder instance.
 *///from  w  ww  .j  av a2s  .com
public static GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();

    // class types
    builder.registerTypeAdapter(Integer.class, new JsonDeserializer<Integer>() {
        @Override
        public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            try {
                return Integer.valueOf(json.getAsInt());
            } catch (NumberFormatException e) {
                return null;
            }
        }
    });
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {

            try {
                return JSON_STRING_DATE.parse(json.getAsString());
            } catch (ParseException e) {
                return null;
            }
        }
    });

    return builder;
}

From source file:com.viettel.ipcclib.WebSocketRTCClient.java

License:Open Source License

@Override
public void onWebSocketMessage(final String msg) {
    //    try {/*from  www  .  j  a v a2s  .c  om*/
    Message message = getGson().fromJson(msg, Message.class);
    //      JSONObject json = new JSONObject(msg);

    AppConfig params = message.getParams();
    if (params != null) {
        Log.i(TAG, "Got appConfig" + msg + " parsing into roomParameters");
        //this.roomParametersFetcher.parseAppConfig(msg);

        Log.i(TAG, "app config: " + msg);
        try {
            //          JSONObject appConfig = new JSONObject(msg);

            String result = message.getResult();
            Log.i(TAG, "client debug ");
            if (!result.equals("SUCCESS")) {
                return;
            }

            //          String params = appConfig.getString("params");
            //          appConfig = new JSONObject(params);
            LinkedList<PeerConnection.IceServer> iceServers = iceServersFromPCConfigJSON(params.getPcConfig());

            AppRTCClient.SignalingParameters signalingParameters = new SignalingParameters(iceServers);

            wsClient.register(connectionParameters.from);
        } catch (JSONException e) {
            signalingEvents.onChannelError("app config JSON parsing error: " + e.toString());
        }
        return;
    }

    //            if (socketState != WebSocketConnectionState.REGISTERED && socketState != WebSocketConnectionState.CONNECTED){
    //                Log.e(TAG, "websocket still in non registered state.");
    //                return;
    //            }
    JsonElement typeJson = message.getType();

    if (typeJson == null || message.getData() == null || !TextUtils.isDigitsOnly(typeJson.getAsString())) {
        return;
    }

    String id = "";
    String response = "";

    MessageData data = message.getData();
    MessageType type = MessageType.getValue(typeJson.getAsInt());
    switch (type) {
    case CUSTOMER_LOGIN:
        //user register
        //            JSONObject userT = json.getJSONObject("data");
        userId = data.getUserId();
        //            userId = userT.getInt("userId");
        //            userName = userT.getString("name");
        userName = data.getName().getAsString();
        //make call;
        socketState = WebSocketChannelClient.WebSocketConnectionState.REGISTERED;
        signalingEvents.onConnected();
        // todo use video
        //        makeCall();
        break;

    case AGENT_INFO_CUSTOMER:
        agentData = message.getData();
        signalingEvents.onAgentJoinConversation(agentData.getFullName());
        break;

    case HAVE_MESSAGE:
        signalingEvents.onMessageCome(data);
        break;

    case MESSAGE:
        conversationId = message.getData().getConversationId();
        signalingEvents.onConversationReady();
        break;

    case SEND_IS_CHAT_TYPING:
        signalingEvents.onAgentTyping(data.getFullName(), data.isTyping());
        break;

    case RESPONSE_AGENT_MISS_CHAT_TO_CUSTOMER:
        signalingEvents.onAgentMissedChat();
        break;

    case VIDEO_CALL: //video call processing
        //            JSONObject dataO = json.getJSONObject("data");
        processVideoCall(message);
        break;

    case AGENT_END_CONVERSATION_CUSTOMER:
        conversationId = -1;
        signalingEvents.onAgentEndConversation(data.getFullName());
        break;

    case RESPONSE_SERVICE_LIST:
        if (data.getServices().isJsonArray()) {

            List<Service> services = GsonWrapper.getGson().fromJson(data.getServices(),
                    new TypeToken<List<Service>>() {
                    }.getType());
            signalingEvents.onServiceListResponse(services);
        }
        break;
    }
    /*
    if(json.has("id")) id = json.getString("id");
            
    if(id.equals("registerResponse")){
            
        response = json.getString("response"); //TODO if not accepted what todo?
        String message = json.getString("message");
            
        if(response.equals("accepted"))      {
            socketState = WebSocketConnectionState.REGISTERED;
        }
            
        else if(response.equals("rejected"))      {
            signalingEvents.onChannelError("register rejected: " + message);
        }
            
        else if(response.equals("skipped")) {
            signalingEvents.onChannelError("register rejected: " + message);                                                                       // Log.e(TAG, "registration was skipped because: "+message);
        }
    }
            
    if(id.equals("registeredUsers")){
        response = json.getString("response");
        signalingEvents.onUserListUpdate(response);
    }
            
    if(id.equals("callResponse")){
        response = json.getString("response");
            
        if(response.startsWith("rejected")) {
            Log.d(TAG, "call got rejected: "+response);
            signalingEvents.onChannelClose();
        }else{
            Log.d(TAG, "sending sdpAnswer: "+response);
            SessionDescription sdp = new SessionDescription(
                    SessionDescription.Type.ANSWER,json.getString("sdpAnswer"));
            
            signalingEvents.onRemoteDescription(sdp);
        }
    }
    if(id.equals("callScreenResponse")){
        response = json.getString("response");
            
        if(response.startsWith("rejected")) {
            Log.d(TAG, "call got rejected: "+response);
            signalingEvents.onChannelScreenClose();
        }else{
            Log.d(TAG, "sending sdpAnswer: "+response);
            SessionDescription sdp = new SessionDescription(
                    SessionDescription.Type.ANSWER,json.getString("sdpAnswer"));
            
            signalingEvents.onRemoteScreenDescription(sdp);
        }
    }
            
    if(id.equals("incomingCall")){
        Log.d(TAG, "incomingCall "+json.toString());
        signalingEvents.onIncomingCall(json.getString("from"));
    }
            
    if(id.equals("incomingScreenCall")){
        Log.d(TAG, "incomingScreenCall "+json.toString());
        signalingEvents.onIncomingScreenCall(json);
    }
            
    if(id.equals("startCommunication")){
        Log.d(TAG, "startCommunication "+json.toString());
        SessionDescription sdp = new SessionDescription(SessionDescription.Type.ANSWER,json.getString("sdpAnswer"));
        signalingEvents.onStartCommunication(sdp);
    }
    if(id.equals("startScreenCommunication")){
        Log.d(TAG, "startScreenCommunication "+json.toString());
        SessionDescription sdp = new SessionDescription(SessionDescription.Type.ANSWER,json.getString("sdpAnswer"));
           // signalingEvents.onStartScreenCommunication(sdp); //remove if not needed!
        signalingEvents.onStartScreenCommunication(sdp);
    }
    if(id.equals("stopCommunication")){
        Log.d(TAG, "stopCommunication "+json.toString());
        signalingEvents.onChannelClose();
    }
    if(id.equals("stopScreenCommunication")){
        Log.d(TAG, "stopCommunication "+json.toString());
        signalingEvents.onChannelScreenClose();
    }
    if(id.equals("iceCandidateScreen")){
            
        JSONObject candidateJson = json.getJSONObject("candidate");
            
        IceCandidate candidate = new IceCandidate(
                candidateJson.getString("sdpMid"),
                candidateJson.getInt("sdpMLineIndex"),
                candidateJson.getString("candidate"));
            
        signalingEvents.onRemoteScreenIceCandidate(candidate);
            
    }
    if(id.equals("iceCandidate")){
        Log.d(TAG, "iceCandidate "+json.toString());
            
        JSONObject candidateJson = json.getJSONObject("candidate");
            
        IceCandidate candidate = new IceCandidate(
                candidateJson.getString("sdpMid"),
                candidateJson.getInt("sdpMLineIndex"),
                candidateJson.getString("candidate"));
            
        signalingEvents.onRemoteIceCandidate(candidate);
    }
            
    if (id.equals("stop")) {
        signalingEvents.onChannelClose();
    }
    if (id.equals("stopScreen")) {
        signalingEvents.onChannelScreenClose();
    }
    */
    //    } catch (JSONException e) {
    //      reportError("WebSocket message JSON parsing error: " + e.toString());
    //    }
}

From source file:com.wallellen.wechat.common.util.json.GsonHelper.java

License:Open Source License

public static Integer getAsInteger(JsonElement element) {
    return isNull(element) ? null : element.getAsInt();
}

From source file:com.wallellen.wechat.cp.util.json.WxCpUserGsonAdapter.java

License:Open Source License

public WxCpUser deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject o = json.getAsJsonObject();
    WxCpUser user = new WxCpUser();
    user.setUserId(GsonHelper.getString(o, "userid"));
    user.setName(GsonHelper.getString(o, "name"));

    if (o.get("department") != null) {
        JsonArray departJsonArray = o.get("department").getAsJsonArray();
        Integer[] departIds = new Integer[departJsonArray.size()];
        int i = 0;
        for (JsonElement jsonElement : departJsonArray) {
            departIds[i++] = jsonElement.getAsInt();
        }/* www  . j  av  a2s. c  o  m*/
        user.setDepartIds(departIds);
    }

    user.setPosition(GsonHelper.getString(o, "position"));
    user.setMobile(GsonHelper.getString(o, "mobile"));
    user.setGender(GsonHelper.getString(o, "gender"));
    user.setTel(GsonHelper.getString(o, "tel"));
    user.setEmail(GsonHelper.getString(o, "email"));
    user.setWeiXinId(GsonHelper.getString(o, "weixinid"));
    user.setAvatar(GsonHelper.getString(o, "avatar"));
    user.setStatus(GsonHelper.getInteger(o, "status"));

    if (GsonHelper.isNotNull(o.get("extattr"))) {
        JsonArray attrJsonElements = o.get("extattr").getAsJsonObject().get("attrs").getAsJsonArray();
        for (JsonElement attrJsonElement : attrJsonElements) {
            WxCpUser.Attr attr = new WxCpUser.Attr(
                    GsonHelper.getString(attrJsonElement.getAsJsonObject(), "name"),
                    GsonHelper.getString(attrJsonElement.getAsJsonObject(), "value"));
            user.getExtAttrs().add(attr);
        }
    }
    return user;
}

From source file:com.wialon.item.ItemIcon.java

License:Apache License

@Override
public boolean updateItemData(String key, JsonElement data) {
    if (super.updateItemData(key, data))
        return true;
    else {//w w w  .  j ava  2s.c  om
        if (key.equals("ugi") && data.getAsNumber() != null)
            setUgi(data.getAsInt());
        else if (key.equals("uri") && data.getAsString() != null)
            setUri(data.getAsString());
        else
            return false;
        return true;
    }
}

From source file:com.wibidata.wibidota.DotaMatchBulkImporter.java

License:Apache License

private static Integer getNullableInt(JsonElement je) {
    return (je == null ? null : je.getAsInt());
}

From source file:crawlers.AudioBooks.java

private static int saveAudioBookByUrl(String urlGet, String tags) throws IOException {
    int numItems = 0;
    List<AudioBookEnt> listAudioBookEnt = new ArrayList<AudioBookEnt>();
    JsonObject jsonObj = readJsonObjectFromUrl(urlGet);
    if (jsonObj != null) {
        JsonElement jsonElementErrorCode = jsonObj.get("status");
        if (jsonElementErrorCode != null && jsonElementErrorCode.getAsInt() == 1) {
            int totalChapter = jsonObj.get("total").getAsInt();

            JsonArray jsonElementData = jsonObj.get("result").getAsJsonArray();
            if (jsonElementData != null && jsonElementData.size() > 0) {
                numItems = jsonElementData.size();
                for (JsonElement tmpJson : jsonElementData) {
                    JsonObject jsonItem = tmpJson.getAsJsonObject();
                    listAudioBookEnt.add(new AudioBookEnt(jsonItem, tags, AudioBookEnt.STATUS.ENABLE));
                }//from  w w  w  .  java  2s . c o m
            }

            //                DatabaseServiceUtils.InsertAppAudioBookEnt(listAudioBookEnt);
        }
    }
    return numItems;
}

From source file:crawlers.Xinh.java

public static void main(String[] args) {
    System.out.println("Crawl Data Xinh!");
    logger.fatal("Crawl Data Xinh!");
    int pageSize = 120;
    String linkXinhCategory = "http://vietmkt.com/xinhxinh/?op=categories";
    String linkHome = "http://vietmkt.com/xinhxinh/?op=home&page=%s&pagesize=%s&device=ipad";
    String linkCategory = "http://vietmkt.com/xinhxinh/?op=getListCate&ID=%s&page=%s&pagesize=%s&device=ipad";

    try {//  www  .j a v  a  2s .com
        //Get Home
        boolean isLoad = true;
        int i = 0;
        while (isLoad) {
            i = (i + 1);
            System.out.println("[Home] Get Image {" + pageSize + "} -> " + i);
            logger.fatal("[Home] Get Image {" + pageSize + "} -> " + i);
            String urlHome = String.format(linkHome, i, pageSize);
            isLoad = saveImageByUrl(urlHome, "Xinh,XHome");
        }

        //Get All Category
        JsonObject jsonObjCategory = readJsonObjectFromUrl(linkXinhCategory);
        if (jsonObjCategory != null) {
            JsonElement jsonElementErrorCode = jsonObjCategory.get("ErrorCode");
            if (jsonElementErrorCode != null && jsonElementErrorCode.getAsInt() == 0) {
                JsonElement jsonElementLoadMore = jsonObjCategory.get("LoadMore");
                JsonArray jsonElementData = jsonObjCategory.get("DATA").getAsJsonArray();
                if (jsonElementData != null && jsonElementData.size() > 0) {
                    for (JsonElement tmpJson : jsonElementData) {
                        String catName = tmpJson.getAsJsonObject().get("NAME_CAT").getAsString();
                        String catKey = tmpJson.getAsJsonObject().get("link").getAsString();

                        isLoad = true;
                        i = 0;
                        while (isLoad) {
                            i = (i + 1);
                            System.out.println("[" + catKey + "] Get Image {" + pageSize + "} -> " + i);
                            logger.fatal("[" + catKey + "] Get Image {" + pageSize + "} -> " + i);
                            String urlCategory = String.format(linkCategory, catKey, i, pageSize);
                            isLoad = saveImageByUrl(urlCategory, "Xinh," + catName + "," + catKey);
                        }
                    }
                }
            }
        }
        System.exit(0);

        //            System.out.println(YoutubeChannel.getChannelId("https://www.youtube.com/channel/UC_iuTdGAVYHMcUZm-srQcRw"));
        //            System.out.println(YoutubeChannel.getChannelId("https://www.youtube.com/user/trucnhanchannel"));
        //            System.out.println(YoutubeChannel.getChannelId("https://www.youtube.com/channel/UC_iuTdGAVYHMcUZm-srQcRw!fdsafasd").length());
    } catch (Exception ex) {

    }
}