Java 类org.json.JSONTokener 实例源码

项目:spanner-jdbc    文件:CloudSpannerConnection.java   
public static String getServiceAccountProjectId(String credentialsPath)
{
    String project = null;
    if (credentialsPath != null)
    {
        try (InputStream credentialsStream = new FileInputStream(credentialsPath))
        {
            JSONObject json = new JSONObject(new JSONTokener(credentialsStream));
            project = json.getString("project_id");
        }
        catch (IOException | JSONException ex)
        {
            // ignore
        }
    }
    return project;
}
项目:MobileMedia    文件:JsonParser.java   
public static String parseIatResult(String json) {
        StringBuffer ret = new StringBuffer();
        try {
            JSONTokener tokener = new JSONTokener(json);
            JSONObject joResult = new JSONObject(tokener);

            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                // 转写结果词,默认使用第一个结果
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                ret.append(obj.getString("w"));
//              如果需要多候选结果,解析数组其他字段
//              for(int j = 0; j < items.length(); j++)
//              {
//                  JSONObject obj = items.getJSONObject(j);
//                  ret.append(obj.getString("w"));
//              }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return ret.toString();
    }
项目:CoinPryc    文件:SecondActivity.java   
protected void onPostExecute(String response) {

            if (response == null) {
                response = "THERE WAS AN ERROR";
                forex = Long.parseLong("1");
            }
            else {
                try {
                    JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
                    JSONObject rates = object.getJSONObject("rates");
                    forex = rates.getLong("INR");

                    System.out.println("Rates " + rates);
                    System.out.println("Forex Rate:" + forex);


                } catch (JSONException e) {
                    // Appropriate error handling code
                    Log.e("Error", e.getMessage());
                }
                Log.i("INFO", response);
            }

        }
项目:alfresco-remote-api    文件:CustomModelImportTest.java   
public void testValidUpload_ExtModuleOnly() throws Exception
{
    File zipFile = getResourceFile("validExtModule.zip");
    PostRequest postRequest = buildMultipartPostRequest(zipFile);

    AuthenticationUtil.setFullyAuthenticatedUser(NON_ADMIN_USER);
    Response response = sendRequest(postRequest, 403);

    AuthenticationUtil.setFullyAuthenticatedUser(CUSTOM_MODEL_ADMIN);
    response = sendRequest(postRequest, 200);

    JSONObject json = new JSONObject(new JSONTokener(response.getContentAsString()));
    assertFalse(json.has("modelName"));

    String extModule = json.getString("shareExtModule");
    Document document = XMLUtil.parse(extModule);
    NodeList nodes = document.getElementsByTagName("id");
    assertEquals(1, nodes.getLength());
    assertNotNull(nodes.item(0).getTextContent());
}
项目:CoinPryc    文件:ThirdActivity.java   
protected void onPostExecute(String response) {

            if (response == null) {
                response = "THERE WAS AN ERROR";
            }
            try {
                JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
                JSONObject rates = object.getJSONObject("rates");
                forex = rates.getLong("INR");

                System.out.println("Rates " + rates);
                System.out.println("Forex Rate:" + forex);


            } catch (JSONException e) {
                // Appropriate error handling code
                Log.e("Error", e.getMessage());
            }
            Log.i("INFO", response);

        }
项目:alfresco-remote-api    文件:CustomModelImportTest.java   
public void testValidUpload_ModelOnly() throws Exception
{
    File zipFile = getResourceFile("validModel.zip");
    PostRequest postRequest = buildMultipartPostRequest(zipFile);

    AuthenticationUtil.setFullyAuthenticatedUser(NON_ADMIN_USER);
    Response response = sendRequest(postRequest, 403);

    AuthenticationUtil.setFullyAuthenticatedUser(CUSTOM_MODEL_ADMIN);
    response = sendRequest(postRequest, 200);

    JSONObject json = new JSONObject(new JSONTokener(response.getContentAsString()));
    String importedModelName = json.getString("modelName");
    importedModels.add(importedModelName);

    assertFalse(json.has("shareExtModule"));

    // Import the same model again
    sendRequest(postRequest, 409); // name conflict
}
项目:strictfp-back-end    文件:VerifyAccount.java   
public boolean verifyStackOverFlowAccount(@NotNull @NonNls String username) {
    try {
        String url = SOFApiRoot + String.format(
                "users?order=asc&min=%s&max=%s&sort=name&inname=%s&site=stackoverflow",
                username,
                username,
                username
        );
        HttpURLConnection conn = HttpURLConnection.class.cast(new URL(url).openConnection());
        if (conn.getResponseCode() != 200) return false;
        JSONTokener tokener = new JSONTokener(new GZIPInputStream(conn.getInputStream()));
        // note that it was compressed
        JSONObject object = JSONObject.class.cast(tokener.nextValue());
        conn.disconnect();
        return object.getJSONArray("items").length() != 0;
        // 特判一下吧还是。。昨晚查询不存在用户返回的是200 ...和一个json
        // 上面打这段注释的,没注意到我判断了返回的结果是否包含有效用户吗 =-= , bug 'fixed'
    } catch (IOException e) {
        throw new RuntimeException("unable to fetch data from stackoverflow", e);
    }
}
项目:yacy_grid_mcp    文件:Data.java   
public static ElasticsearchClient getIndex() {
    if (index == null) {
        // create index
        String elasticsearchAddress = config.getOrDefault("grid.elasticsearch.address", "localhost:9300");
        String elasticsearchClusterName = config.getOrDefault("grid.elasticsearch.clusterName", "");
        String elasticsearchWebIndexName= config.getOrDefault("grid.elasticsearch.webIndexName", "web");
        Path webMappingPath = Paths.get("conf/mappings/web.json");
        if (webMappingPath.toFile().exists()) try {
            index = new ElasticsearchClient(new String[]{elasticsearchAddress}, elasticsearchClusterName.length() == 0 ? null : elasticsearchClusterName);
            index.createIndexIfNotExists(elasticsearchWebIndexName, 1 /*shards*/, 1 /*replicas*/);
            String mapping = new String(Files.readAllBytes(webMappingPath));
            JSONObject mo = new JSONObject(new JSONTokener(mapping));
            mo = mo.getJSONObject("mappings").getJSONObject("_default_");
            index.setMapping("web", mo.toString());
            Data.logger.info("Connected elasticsearch at " + getHost(elasticsearchAddress));
        } catch (IOException | NoNodeAvailableException e) {
            index = null; // index not available
            Data.logger.info("Failed connecting elasticsearch at " + getHost(elasticsearchAddress) + ": " + e.getMessage(), e);
        } else {
            Data.logger.info("no web index mapping available, no connection to elasticsearch attempted");
        }
    }
    return index;
}
项目:alfresco-remote-api    文件:QuickShareRestApiTest.java   
/**
 * This test verifies that copying a shared node does not across the shared aspect and it's associated properties.
 * @throws IOException 
 * @throws UnsupportedEncodingException 
 * @throws JSONException 
 * @throws FileNotFoundException 
 * @throws FileExistsException 
 */
public void testCopy() throws UnsupportedEncodingException, IOException, JSONException, FileExistsException, FileNotFoundException 
{
    final int expectedStatusOK = 200;

    String testNodeRef = testNode.toString().replace("://", "/");

    // As user one ...

    // share
    Response rsp = sendRequest(new PostRequest(SHARE_URL.replace("{node_ref_3}", testNodeRef), "", APPLICATION_JSON), expectedStatusOK, USER_ONE);
    JSONObject jsonRsp = new JSONObject(new JSONTokener(rsp.getContentAsString()));
    String sharedId = jsonRsp.getString("sharedId");
    assertNotNull(sharedId);
    assertEquals(22, sharedId.length()); // note: we may have to adjust/remove this check if we change length of id (or it becomes variable length)

    AuthenticationUtil.setFullyAuthenticatedUser(USER_ONE);
    FileInfo copyFileInfo = fileFolderService.copy(testNode, userOneHome, "Copied node");
    NodeRef copyNodeRef = copyFileInfo.getNodeRef();

    assertFalse(nodeService.hasAspect(copyNodeRef, QuickShareModel.ASPECT_QSHARE));
}
项目:PixelDungeonTC    文件:Bundle.java   
public static Bundle read( InputStream stream ) {

    try {
        BufferedReader reader = new BufferedReader( new InputStreamReader( stream ) );

        StringBuilder builder = new StringBuilder();

        char[] buffer = new char[0x2000];
        int count = reader.read( buffer );
        while (count > 0) {
            for (int i=0; i < count; i++) {
                buffer[i] ^= XOR_KEY;
            }
            builder.append( buffer, 0, count );
            count = reader.read( buffer );
        }

        JSONObject json = (JSONObject)new JSONTokener( builder.toString() ).nextValue();
        reader.close();

        return new Bundle( json );
    } catch (Exception e) {
        return null;
    }
}
项目:kognitivo    文件:GraphResponse.java   
static List<GraphResponse> createResponsesFromString(
        String responseString,
        HttpURLConnection connection,
        GraphRequestBatch requests
) throws FacebookException, JSONException, IOException {
    JSONTokener tokener = new JSONTokener(responseString);
    Object resultObject = tokener.nextValue();

    List<GraphResponse> responses = createResponsesFromObject(
            connection,
            requests,
            resultObject);
    Logger.log(
            LoggingBehavior.REQUESTS,
            RESPONSE_LOG_TAG,
            "Response\n  Id: %s\n  Size: %d\n  Responses:\n%s\n",
            requests.getId(),
            responseString.length(),
            responses);

    return responses;
}
项目:AssistantBySDK    文件:AudioJsonParser.java   
public static String parseIatResult(String json) {
        if(json.startsWith("<"))return AudioXmlParser.parseXmlResult(json,0);
        StringBuffer ret = new StringBuffer();
        try {
            JSONTokener tokener = new JSONTokener(json);
            JSONObject joResult = new JSONObject(tokener);

            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                // 转写结果词,默认使用第一个结�?
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                ret.append(obj.getString("w"));
//              如果�?��多�?选结果,解析数组其他字段
//              for(int j = 0; j < items.length(); j++)
//              {
//                  JSONObject obj = items.getJSONObject(j);
//                  ret.append(obj.getString("w"));
//              }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return ret.toString();
    }
项目:KotlinStudy    文件:JsonParser.java   
public static String parseIatResult(String json) {
        StringBuffer ret = new StringBuffer();
        try {
            JSONTokener tokener = new JSONTokener(json);
            JSONObject joResult = new JSONObject(tokener);

            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                // 转写结果词,默认使用第一个结果
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                ret.append(obj.getString("w"));
//              如果需要多候选结果,解析数组其他字段
//              for(int j = 0; j < items.length(); j++)
//              {
//                  JSONObject obj = items.getJSONObject(j);
//                  ret.append(obj.getString("w"));
//              }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return ret.toString();
    }
项目:alfresco-remote-api    文件:ResultMapperTests.java   
private ResultSet mockResultset(List<Long> archivedNodes, List<Long> versionNodes) throws JSONException
{

    NodeService nodeService = mock(NodeService.class);
    when(nodeService.getNodeRef(any())).thenAnswer(new Answer<NodeRef>() {
        @Override
        public NodeRef answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            //If the DBID is in the list archivedNodes, instead of returning a noderef return achivestore noderef
            if (archivedNodes.contains(args[0])) return new NodeRef(StoreRef.STORE_REF_ARCHIVE_SPACESSTORE, GUID.generate());
            if (versionNodes.contains(args[0])) return new NodeRef(StoreMapper.STORE_REF_VERSION2_SPACESSTORE, GUID.generate()+args[0]);
            return new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, GUID.generate());
        }
    });

    SearchParameters sp = new SearchParameters();
    sp.setBulkFetchEnabled(false);
    JSONObject json = new JSONObject(new JSONTokener(JSON_REPONSE));
    ResultSet results = new SolrJSONResultSet(json,sp,nodeService, null, LimitBy.FINAL_SIZE, 10);
    return results;
}
项目:alfresco-repository    文件:SpellCheckDecisionManagerTest.java   
public JSONObject createJsonSearchRequest(String searchTerm) throws JSONException
{
    String requestStr = "{"
                + "\"queryConsistency\" : \"DEFAULT\","
                + "\"textAttributes\" : [],"
                + "\"allAttributes\" : [],"
                + "\"templates\" : [{"
                + "\"template\" : \"%(cm:name cm:title cm:description ia:whatEvent ia:descriptionEvent lnk:title lnk:description TEXT TAG)\","
                + "\"name\" : \"keywords\""
                + "}"
                + "],"
                + "\"authorities\" : [\"GROUP_EVERYONE\", \"ROLE_ADMINISTRATOR\", \"ROLE_AUTHENTICATED\", \"admin\"],"
                + "\"tenants\" : [\"\"],"
                + "\"query\" : \"("
                + searchTerm
                + "  AND (+TYPE:\\\"cm:content\\\" OR +TYPE:\\\"cm:folder\\\")) AND -TYPE:\\\"cm:thumbnail\\\" AND -TYPE:\\\"cm:failedThumbnail\\\" AND -TYPE:\\\"cm:rating\\\" AND -TYPE:\\\"st:site\\\" AND -ASPECT:\\\"st:siteContainer\\\" AND -ASPECT:\\\"sys:hidden\\\" AND -cm:creator:system AND -QNAME:comment\\\\-*\","
                + "\"locales\" : [\"en\"],"
                + "\"defaultNamespace\" : \"http://www.alfresco.org/model/content/1.0\","
                + "\"defaultFTSFieldOperator\" : \"AND\"," + "\"defaultFTSOperator\" : \"AND\"" + "}";

    InputStream is = new ByteArrayInputStream(requestStr.getBytes());
    Reader reader = new BufferedReader(new InputStreamReader(is));
    JSONObject json = new JSONObject(new JSONTokener(reader));
    return json;
}
项目:AndroidBackendlessChat    文件:Response.java   
static List<Response> createResponsesFromString(String responseString, HttpURLConnection connection,
        RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException {
    JSONTokener tokener = new JSONTokener(responseString);
    Object resultObject = tokener.nextValue();

    List<Response> responses = createResponsesFromObject(connection, requests, resultObject, isFromCache);
    Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n  Id: %s\n  Size: %d\n  Responses:\n%s\n",
            requests.getId(), responseString.length(), responses);

    return responses;
}
项目:appinventor-extensions    文件:JsonUtil.java   
public static Object getObjectFromJson(String jsonString) throws JSONException {
    if ((jsonString == null) || jsonString.equals("")) {
    // We'd like the empty string to decode to the empty string.  Form.java
    // relies on this for the case where there's an activity result with no intent data.
    // We handle this case explicitly since nextValue() appears to throw an error
    // when given the empty string.
    return "";
  } else {
    final Object value = (new JSONTokener(jsonString)).nextValue();
    // Note that the JSONTokener may return a value equals() to null.
    if (value == null || value.equals(null)) {
      return null;
    } else if ((value instanceof String) ||
        (value instanceof Number) ||
        (value instanceof Boolean)) {
      return value;
    } else if (value instanceof JSONArray) {
      return getListFromJsonArray((JSONArray)value);
    } else if (value instanceof JSONObject) {
      return getListFromJsonObject((JSONObject)value);
    }
    throw new JSONException("Invalid JSON string.");
  }
}
项目:KotlinStudy    文件:JsonParser.java   
public static String parseTransResult(String json,String key) {
    StringBuffer ret = new StringBuffer();
    try {
        JSONTokener tokener = new JSONTokener(json);
        JSONObject joResult = new JSONObject(tokener);
        String errorCode = joResult.optString("ret");
        if(!errorCode.equals("0")) {
            return joResult.optString("errmsg");
        }
        JSONObject transResult = joResult.optJSONObject("trans_result");
        ret.append(transResult.optString(key));
        /*JSONArray words = joResult.getJSONArray("results");
        for (int i = 0; i < words.length(); i++) {
            JSONObject obj = words.getJSONObject(i);
            ret.append(obj.getString(key));
        }*/
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ret.toString();
}
项目:ESPD    文件:Bundle.java   
public static Bundle read(InputStream stream) {

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

            StringBuilder all = new StringBuilder();
            String line = reader.readLine();
            while (line != null) {
                all.append(line);
                line = reader.readLine();
            }

            JSONObject json = (JSONObject) new JSONTokener(all.toString()).nextValue();
            reader.close();

            return new Bundle(json);
        } catch (Exception e) {
            return null;
        }
    }
项目:alfresco-remote-api    文件:FacetRestApiTest.java   
public void testGetAllFacetableProperties() throws Exception
{
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        @Override public Void doWork() throws Exception
        {
            final Response rsp = sendRequest(new GetRequest(GET_ALL_FACETABLE_PROPERTIES_URL), 200);

            // For now, we'll only perform limited testing of the response as we primarily
            // want to know that the GET call succeeded and that it correctly identified
            // *some* facetable properties.
            JSONObject jsonRsp = new JSONObject(new JSONTokener(rsp.getContentAsString()));

            JSONObject data = jsonRsp.getJSONObject("data");
            JSONArray properties = data.getJSONArray(FacetablePropertiesGet.PROPERTIES_KEY);

            final int arbitraryLimit = 25;
            assertTrue("Expected 'many' properties, but found 'not very many'", properties.length() > arbitraryLimit);

            return null;
        }
    }, SEARCH_ADMIN_USER);
}
项目:exciting-app    文件:JsonParser.java   
public static String parseIatResult(String json) {
        StringBuffer ret = new StringBuffer();
        try {
            JSONTokener tokener = new JSONTokener(json);
            JSONObject joResult = new JSONObject(tokener);

            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                // 转写结果词,默认使用第一个结果
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                ret.append(obj.getString("w"));
//              如果需要多候选结果,解析数组其他字段
//              for(int j = 0; j < items.length(); j++)
//              {
//                  JSONObject obj = items.getJSONObject(j);
//                  ret.append(obj.getString("w"));
//              }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return ret.toString();
    }
项目:alfresco-remote-api    文件:FacetRestApiTest.java   
public void testGetFacetablePropertiesForSpecificContentClasses() throws Exception
{
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        @Override public Void doWork() throws Exception
        {
            final Response rsp = sendRequest(new GetRequest(GET_SPECIFIC_FACETABLE_PROPERTIES_URL.replace("{classname}", "cm:content")), 200);

            // For now, we'll only perform limited testing of the response as we primarily
            // want to know that the GET call succeeded and that it correctly identified
            // *some* facetable properties.
            JSONObject jsonRsp = new JSONObject(new JSONTokener(rsp.getContentAsString()));

            JSONObject data = jsonRsp.getJSONObject("data");
            JSONArray properties = data.getJSONArray(FacetablePropertiesGet.PROPERTIES_KEY);

            final int arbitraryLimit = 100;
            assertTrue("Expected 'not very many' properties, but found 'many'", properties.length() < arbitraryLimit);

            return null;
        }
    }, SEARCH_ADMIN_USER);
}
项目:Avalon-GroupCleaner    文件:CoolQGroupOperator.java   
public static List<GroupMember> getGroupMembers(long groupUid) {
    Map<String, Object> object = new HashMap<>();
    Group group = getGroup(groupUid);
    object.put("group_id", groupUid);
    JSONArray array = ((JSONObject) new JSONTokener(sendRequest("/get_group_member_list", object))
            .nextValue()).getJSONArray("data");
    List<GroupMember> members = new ArrayList<>();
    for (Object thisObject : array) {
        JSONObject item = (JSONObject) thisObject;
        if (!item.has("card"))
            System.err.println("无法获取到昵称为 " + item.getString("nickname") + " 的群成员的相关信息,已略过。");
        else
            members.add(new GroupMember(
                    group,
                    item.getLong("user_id"),
                    item.getString("nickname"),
                    item.getString("card"),
                    item.getLong("last_sent_time"),
                    GroupMemberRoleEnum.fromString(item.getString("role")),
                    item.getBoolean("unfriendly")
            ));
    }
    return members;
}
项目:Avalon-GroupCleaner    文件:KickNextTime.java   
public void handle(long groupUid, Rule rule) throws IOException {
    if (!Constant._KICK_NEXT_TIME_LIST().exists())
        return;
    try (FileReader reader = new FileReader(Constant._KICK_NEXT_TIME_LIST())) {
        JSONObject object = (JSONObject) new JSONTokener(reader).nextValue();
        JSONArray groupMember = object.getJSONArray(String.valueOf(groupUid));

        for (Object thisGroupMemberObject : groupMember) {
            long thisGroupMember =
                    thisGroupMemberObject instanceof Long ?
                            (long) thisGroupMemberObject :
                            (long) (int) thisGroupMemberObject;
            GroupMember member = CoolQGroupOperator.getGroupMember(groupUid, thisGroupMember);
            String kick = rule.kickNextTime(member);
            if (kick != null && !kick.isEmpty())
                member.kick();
            System.out.println("群员 " + thisGroupMember + " 由于未做出修正而被移出本群。");
        }
    }
    System.out.println("文件删除状态:" + Constant._KICK_NEXT_TIME_LIST().delete());
}
项目:alfresco-remote-api    文件:CustomModelImportTest.java   
public void testValidUpload_ModelAndExtModule() throws Exception
{
    File zipFile = getResourceFile("validModelAndExtModule.zip");
    PostRequest postRequest = buildMultipartPostRequest(zipFile);

    AuthenticationUtil.setFullyAuthenticatedUser(NON_ADMIN_USER);
    Response response = sendRequest(postRequest, 403);

    AuthenticationUtil.setFullyAuthenticatedUser(CUSTOM_MODEL_ADMIN);
    response = sendRequest(postRequest, 200);

    JSONObject json = new JSONObject(new JSONTokener(response.getContentAsString()));

    String importedModelName = json.getString("modelName");
    importedModels.add(importedModelName);

    String extModule = json.getString("shareExtModule");
    Document document = XMLUtil.parse(extModule);
    NodeList nodes = document.getElementsByTagName("id");
    assertEquals(1, nodes.getLength());
    assertNotNull(nodes.item(0).getTextContent());
}
项目:Shadbot    文件:PremiumManager.java   
@DataInit
public static void init() throws JSONException, IOException {
    if(!FILE.exists()) {
        try (FileWriter writer = new FileWriter(FILE)) {
            JSONObject defaultObj = new JSONObject()
                    .put(DONATORS, new JSONObject())
                    .put(UNUSED_RELICS, new JSONArray());

            writer.write(defaultObj.toString(Config.JSON_INDENT_FACTOR));
        }
    }

    try (InputStream stream = FILE.toURI().toURL().openStream()) {
        premiumObj = new JSONObject(new JSONTokener(stream));
    }

    premiumObj.getJSONArray(UNUSED_RELICS)
            .forEach(relicObj -> UNUSED_RELICS_LIST.add(new Relic((JSONObject) relicObj)));
}
项目:boohee_v5.6    文件:AddCardToWXCardPackage.java   
public void fromBundle(Bundle bundle) {
    super.fromBundle(bundle);
    if (this.cardArrary == null) {
        this.cardArrary = new LinkedList();
    }
    String string = bundle.getString("_wxapi_add_card_to_wx_card_list");
    if (string != null && string.length() > 0) {
        try {
            JSONArray jSONArray = ((JSONObject) new JSONTokener(string).nextValue())
                    .getJSONArray("card_list");
            for (int i = 0; i < jSONArray.length(); i++) {
                JSONObject jSONObject = jSONArray.getJSONObject(i);
                WXCardItem wXCardItem = new WXCardItem();
                wXCardItem.cardId = jSONObject.optString("card_id");
                wXCardItem.cardExtMsg = jSONObject.optString("card_ext");
                wXCardItem.cardState = jSONObject.optInt("is_succ");
                this.cardArrary.add(wXCardItem);
            }
        } catch (Exception e) {
        }
    }
}
项目:boohee_v5.6    文件:LEYUApplication.java   
public void handleMessage(Message msg) {
    super.handleMessage(msg);
    String smsg = msg.obj.toString();
    if (msg.what == 0) {
        try {
            LEYUApplication.dev_access_token = ((JSONObject) new JSONTokener(smsg)
                    .nextValue()).getString("access_token");
            LEYUApplication.set("leyu_dev_access_token", LEYUApplication.dev_access_token);
            LEYUApplication.this._callback.ReturnAccessToken(LEYUApplication
                    .dev_access_token);
        } catch (JSONException ex) {
            ex.printStackTrace();
            LEYUApplication.this._callback.onFailed(ex.getMessage());
        }
    } else if (msg.what == 1) {
        LEYUApplication.this._callback.OnCompleted(smsg);
    } else if (msg.what == 2) {
        LEYUApplication.this._callback.onFailed(smsg);
    }
}
项目:sealtalk-android-master    文件:RecognizerView.java   
private String parseIatResult(String json) {
        {
            StringBuffer ret = new StringBuffer();
            JSONTokener jsonTokener = new JSONTokener(json);
            try {
                JSONObject jsonObject = new JSONObject(jsonTokener);
                JSONArray jsonArray = jsonObject.getJSONArray("ws");
                for (int i = 0; i < jsonArray.length(); ++i) {
                    // 转写结果词,默认使用第一个结果
                    JSONArray items = jsonArray.getJSONObject(i).getJSONArray("cw");
                    JSONObject obj = items.getJSONObject(0);
//              如果需要多候选结果,解析数组其他字段0
//              for(int j = 0; j < items.length(); j++)
//              {
//                  JSONObject obj = items.getJSONObject(j);
//                  ret.append(obj.getString("w"));
//              }
                    ret.append(obj.getString("w"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return ret.toString();
        }

    }
项目:starcor.xul    文件:XulBinding.java   
@Override
public Object finalItem() {
    if (_content != null) {
        String content = _content.trim();
        _content = null;
        try {
            Object jsonObj = new JSONTokener(content).nextValue();
            if (jsonObj instanceof JSONObject || jsonObj instanceof JSONArray) {
                parseJsonObject(jsonObj, this, null);
                content = null;
            }
        } catch (JSONException e) {
        }
        if (!TextUtils.isEmpty(content)) {
            _binding._dataUrl = content;
        }
    }

    XulBinding binding = _binding;
    FinalCallback<XulBinding> callback = _callback;

    _Builder.recycle(this);

    callback.onFinal(binding);
    return binding;
}
项目:CoinPryc    文件:FourthActivity.java   
protected void onPostExecute(String response) {
    if (response == null) {
        response = "THERE WAS AN ERROR";
    }
    try {

        JSONArray jsonArray = (JSONArray) new JSONTokener(response).nextValue();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject json_data = jsonArray.getJSONObject(i);
            // Users user = new Users();
            name = json_data.getString("name");
            symbol = json_data.getString("symbol");
            rank = json_data.getString("rank");
            price = json_data.getString("price_usd");
            change = json_data.getString("percent_change_24h");

            System.out.println(name + symbol + rank + price);
            addData();
            System.out.println("Data Added");
            //user.setUsername(json_data.getString("username"));
            //user.setEmail(json_data.getString("email"));
            //users.add(user);
        }

    } catch (JSONException e) {
        // Appropriate error handling code
    }
    Log.i("INFO", response);


}
项目:CoinPryc    文件:AddActivity.java   
protected void onPostExecute(String response) {
    if (response == null) {
        response = "THERE WAS AN ERROR";
    }
    try {

        JSONArray jsonArray = (JSONArray) new JSONTokener(response).nextValue();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject json_data = jsonArray.getJSONObject(i);
            // Users user = new Users();
            name = json_data.getString("name");
           // symbol = json_data.getString("symbol");
            //rank = json_data.getString("rank");
            //price = json_data.getString("price_usd");
            //change = json_data.getString("percent_change_24h");

            System.out.println(name);
            list.add(name);
           // addData();
            System.out.println("Data Added");
            //user.setUsername(json_data.getString("username"));
            //user.setEmail(json_data.getString("email"));
            //users.add(user);
        }

    } catch (JSONException e) {
        // Appropriate error handling code
    }
    Log.i("INFO", response);
    spinner.setVisibility(View.GONE);


}
项目:CoinPryc    文件:SecondActivity.java   
protected void onPostExecute(String response) {
    String zebpaybuy=null;
    String zebpaysell=null;
    if (response == null) {
        response = "THERE WAS AN ERROR";
        zebpaybuy = "0";
        zebpaysell = "0";
        Toast.makeText(getApplicationContext(), "Bad Response", Toast.LENGTH_SHORT).show();
    }
    else {
        try {
            JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
            zebpaybuy = object.getString("buy");
            zebpaysell = object.getString("sell");
            Toast.makeText(getApplicationContext(), "Retrieving Data", Toast.LENGTH_SHORT).show();

        } catch (JSONException e) {
            // Appropriate error handling code
        }
        Log.i("INFO", response);
    }

        textView1.setText(zebpaybuy);
        textView2.setText(zebpaysell);

        min = Double.parseDouble(zebpaybuy);
        System.out.println("The Minimum price is " + min);

        if (Double.parseDouble(zebpaybuy) !=0 && Double.parseDouble(zebpaybuy) <= min ) {
            flag = 1;
        }

        max = Double.parseDouble(zebpaysell);
        System.out.println("The Maximum price is " + max);

        if (Double.parseDouble(zebpaysell) >= max) {
            flag1 = 1;
        }
}
项目:alfresco-remote-api    文件:FormRestApiGet_Test.java   
@SuppressWarnings("unchecked")
public void testJsonFormData() throws Exception
{
    JSONObject jsonPostData = createItemJSON(this.referencingDocNodeRef);
    String jsonPostString = jsonPostData.toString();
    Response rsp = sendRequest(new PostRequest(FORM_DEF_URL, 
                jsonPostString, APPLICATION_JSON), 200);
    String jsonResponseString = rsp.getContentAsString();

    JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString));
    assertNotNull(jsonParsedObject);

    JSONObject rootDataObject = (JSONObject)jsonParsedObject.get("data");

    JSONObject formDataObject = (JSONObject)rootDataObject.get("formData");
    List<String> keys = new ArrayList<String>();
    for (Iterator iter = formDataObject.keys(); iter.hasNext(); )
    {
        String nextFieldName = (String)iter.next();
        assertEquals("Did not expect to find a colon char in " + nextFieldName,
                    -1, nextFieldName.indexOf(':'));
        keys.add(nextFieldName);
    }
    // Threshold is a rather arbitrary number. I simply want to ensure that there
    // are *some* entries in the formData hash.
    final int threshold = 5;
    int actualKeyCount = keys.size();
    assertTrue("Expected more than " + threshold +
            " entries in formData. Actual: " + actualKeyCount, actualKeyCount > threshold);
}
项目:CoinPryc    文件:ThirdActivity.java   
protected void onPostExecute(String response) {
    String zebpaybuy = null;
    String zebpaysell = null;
    if (response == null) {
        response = "THERE WAS AN ERROR";
    }
    try {
        JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
        zebpaybuy = object.getString("bid");
        zebpaysell = object.getString("ask");

    } catch (JSONException e) {
        // Appropriate error handling code
    }
    Log.i("INFO", response);
    textView3.setText(zebpaybuy);
    textView4.setText(zebpaysell);
    if (Double.parseDouble(zebpaybuy)<=min)
    {
        min = Double.parseDouble(zebpaybuy);

        flag =2;
    }

    if (Double.parseDouble(zebpaysell)>=max)
    {
        max = Double.parseDouble(zebpaysell);
        flag1 =2;
    }

}
项目:CoinPryc    文件:ThirdActivity.java   
protected void onPostExecute(String response) {
    long zebpaybuy = 0;
    long zebpaysell = 0;
    String coinsec1 = null;
    String coinsec2 = null;

    if (response == null) {
        response = "THERE WAS AN ERROR";
    }
    try {
        JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
        JSONObject message = object.getJSONObject("btcusd");
        zebpaybuy = message.getLong("ask");
        zebpaysell = message.getLong("bid");
        System.out.println("ASk : " + zebpaybuy + "Bid:" + zebpaysell);

        // zebpaybuy=(zebpaybuy);
        //zebpaysell=zebpaysell;
        coinsec1 = Long.toString(zebpaybuy);
        coinsec2 = Long.toString(zebpaysell);

    } catch (JSONException e) {
        // Appropriate error handling code
    }
    Log.i("INFO", response);
    textView5.setText(coinsec1);
    textView6.setText(coinsec2);

    if (Double.parseDouble(coinsec1)<=min)
    {
        min = Double.parseDouble(coinsec1);
        flag =3;
    }
    if (Double.parseDouble(coinsec2)>=max)
    {
        max = Double.parseDouble(coinsec2);
        flag1 =3;
    }

}
项目:MobileMedia    文件:JsonParser.java   
public static String parseGrammarResult(String json) {
    StringBuffer ret = new StringBuffer();
    try {
        JSONTokener tokener = new JSONTokener(json);
        JSONObject joResult = new JSONObject(tokener);

        JSONArray words = joResult.getJSONArray("ws");
        for (int i = 0; i < words.length(); i++) {
            JSONArray items = words.getJSONObject(i).getJSONArray("cw");
            for(int j = 0; j < items.length(); j++)
            {
                JSONObject obj = items.getJSONObject(j);
                if(obj.getString("w").contains("nomatch"))
                {
                    ret.append("没有匹配结果.");
                    return ret.toString();
                }
                ret.append("【结果】" + obj.getString("w"));
                ret.append("【置信度】" + obj.getInt("sc"));
                ret.append("\n");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        ret.append("没有匹配结果.");
    } 
    return ret.toString();
}
项目:alfresco-remote-api    文件:FormRestApiGet_Test.java   
public void testJsonSelectedFields() throws Exception
{
    JSONObject jsonPostData = createItemJSON(this.referencingDocNodeRef);
    JSONArray jsonFields = new JSONArray();
    jsonFields.put("cm:name");
    jsonFields.put("cm:title");
    jsonFields.put("cm:publisher");
    jsonPostData.put("fields", jsonFields);

    // Submit the JSON request.
    String jsonPostString = jsonPostData.toString();        
    Response rsp = sendRequest(new PostRequest(FORM_DEF_URL, jsonPostString,
            APPLICATION_JSON), 200);

    String jsonResponseString = rsp.getContentAsString();
    JSONObject jsonParsedObject = new JSONObject(new JSONTokener(jsonResponseString));
    assertNotNull(jsonParsedObject);

    JSONObject rootDataObject = (JSONObject)jsonParsedObject.get("data");
    JSONObject definitionObject = (JSONObject)rootDataObject.get("definition");
    JSONArray fieldsArray = (JSONArray)definitionObject.get("fields");
    assertEquals("Expected 2 fields", 2, fieldsArray.length());

    // get the name and title definitions
    JSONObject nameField = (JSONObject)fieldsArray.get(0);
    JSONObject titleField = (JSONObject)fieldsArray.get(1);
    String nameFieldDataKey = nameField.getString("dataKeyName");
    String titleFieldDataKey = titleField.getString("dataKeyName");

    // get the data and check it
    JSONObject formDataObject = (JSONObject)rootDataObject.get("formData");
    assertNotNull("Expected to find cm:name data", formDataObject.get(nameFieldDataKey));
    assertNotNull("Expected to find cm:title data", formDataObject.get(titleFieldDataKey));
    assertEquals(TEST_FORM_TITLE, formDataObject.get("prop_cm_title"));
}
项目:school-website    文件:StringUtils.java   
/**
 * Is json array json array.
 *  是否是JSONObject
 * @param string the string
 * @return the json array
 */
public static JSONObject isJSONObject(String string) {
    if (isEmpty(string))
        return null;
    Object json = new JSONTokener(string).nextValue();
    if (json instanceof JSONObject) {
        return (JSONObject) json;
    }
    return null;
}
项目:yacy_grid_mcp    文件:AbstractBrokerListener.java   
private void handleMessage(final MessageContainer<byte[]> mc, final String processName, final int processNumber) {
    String payload = new String(mc.getPayload(), StandardCharsets.UTF_8);
    JSONObject json = new JSONObject(new JSONTokener(payload));
    final SusiThought process = new SusiThought(json);
    final JSONArray data = process.getData();
    final List<SusiAction> actions = process.getActions();

    // loop though all actions
    actionloop: for (int ac = 0; ac < actions.size(); ac++) {
        SusiAction action = actions.get(ac);
        String type = action.getStringAttr("type");
        String queue = action.getStringAttr("queue");

        // check if the credentials to execute the queue are valid
        if (type == null || type.length() == 0 || queue == null || queue.length() == 0) {
            Data.logger.info("bad message in queue, continue");
            continue actionloop;
        }

        // check if this is the correct queue
        if (!type.equals(this.service.name())) {
            Data.logger.info("wrong message in queue: " + type + ", continue");
            try {
                loadNextAction(action, process.getData()); // put that into the correct queue
            } catch (Throwable e) {
                Data.logger.warn("", e);
            }
            continue actionloop;
        }

        // process the action using the previously acquired execution thread
        //this.threadPool.execute(new ActionProcess(action, data));
        new ActionProcess(action, data, processName, processNumber).run(); // run, not start: we execute this in the current thread
    }
}