2014-03-24 111 views
0

因此,我使用http post方法從API請求一些數據,然後收到一個JSON響應,然後看到類似於JSON響應的字符串,如下所示:將字符串中的數字轉換爲列表java

{"status": "OK", "results": [{"score": 0.0, "id": "2"}, {"score": 1.0, "id": "3"}, {"score": 0.0, "id": "0"}, {"score": 0.0, "id": "1"}, {"score": 0.0, "id": "6"}, {"score": 0.23606, "id": "7"}, {"score": 0.0, "id": "4"}, {"score": -0.2295, "id": "5"}, {"score": 0.41086, "id": "8"}, {"score": 0.39129, "id": "9"}]} 

我想從這個列表中提取數字,或者更好地檢查多少個數字在0.2-1.0之間,如果這個條件是真的,則增加一個整數值。

比如我想要做這樣的事,但我只是找不到正確的語法我。

if(responseString.contains("0.0-0.2") 
    { 
    OccurencesNeutral++ 
    } 
    if(responseString.contains("0.2-1.0") 
    { 
    OccurencesPositive++ 
    } 

回答

2

在處理JSON時,應該使用JSONObject API。在你的情況,這樣的事情應該工作:

try { 
    JSONObject json = new JSONObject(theStringYouGot); 
    JSONArray results = json.getJSONArray("results"); 
    for (int i = 0; i < results.length(); i++) { 
     JSONObject data = results.getJSONObject(i); 
     double score = data.getDouble("score"); 
    } 
} catch (JSONException x) { 
    // Handle exception... 
} 

在代碼中,你應該用清潔的代碼常數代替硬編碼的字段名。

+0

哎克里斯 - 這似乎是正是我要找的,但我發現用線的JSONObject數據= results1.get(我)的錯誤;我對JSON相當陌生,因此爲什麼我將響應者直接更改爲字符串 – user3456401

+0

我更新了我的答案,現在能工作嗎?我只是從腦海中寫下來的,所以它可能有流浪語法錯誤... – BadIdeaException

+0

它現在正在使用results1.get(i)行,但它看起來不像data.get(「score」 )被宣佈爲雙重? – user3456401

0

如果你是使用JSON libraray,就會有方法序列化和創建字符串對象,這樣你就可以用正確的get方法尋找新的對象的數量。

例如在org.json您可以在常規做

JSONObject jsonObj = new JSONObject("your string"); 
0

代碼這樣做如果你想嘗試的正則表達式這(更改0.2〜參數)

def JsonSlurper js = new JsonSlurper() 
def o = js.parseText(jsonStr) 
def (neu, pos) = [0, 0] 
o.results.each { 
    if (it.score <= 0.2) neu ++ 
    else pos ++ 
} 
println "$neu $pos" 
0

int OccurencesNeutral=0; 
    int OccurencesPositive=0; 
    String regex="((-?\\d+)\\.(\\d+))"; 
    String str="{\"status\": \"OK\", \"results\": [{\"score\": 0.0, \"id\": \"2\"}, {\"score\": 1.0, \"id\": \"3\"}, {\"score\": 0.0, \"id\": \"0\"}, {\"score\": 0.0, \"id\": \"1\"}, {\"score\": 0.0, \"id\": \"6\"}, {\"score\": 0.23606, \"id\": \"7\"}, {\"score\": 0.0, \"id\": \"4\"}, {\"score\": -0.2295, \"id\": \"5\"}, {\"score\": 0.41086, \"id\": \"8\"}, {\"score\": 0.39129, \"id\": \"9\"}]}"; 

    Pattern p=Pattern.compile(regex); 
    Matcher m=p.matcher(str); 

    float f=0; 
    while(m.find()){ 
     f=Float.parseFloat(m.group()); 
     if(f>0 && f<0.2) 
      OccurencesNeutral++; 
     if(f>0.2 && f<1.0) 
      OccurencesPositive++; 
    } 

    System.out.println("Neutral="+OccurencesNeutral+"\t"+"Positives="+OccurencesPositive); 
+0

嘿RKC感謝您的回覆,這似乎不過是工作在大多數情況下,如果比分是說比如-0.23553它仍然會被添加到occurrencesPositive,確實爲負數我嘗試添加如果(F <0.0這個表達式工作){occurrencesNeg ++}但無濟於事 – user3456401

+0

上面修改了我的正則表達式。現在它也適用於負數。 – RKC

+0

Brillance!非常感謝,只是爲了幫助我理解它正在搜索字符串,然後查找數字的模式(現在可以減去)。那麼另一個數字是否正確那麼當發現這種情況時,我們使用匹配器來分配我們想要的類型,即pos,neg或neu – user3456401