2014-03-24 114 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