2010-10-14 114 views
1

我有一個像這樣的字符串。數組解析的字符串

{"type":"broad","Text":"cat"},{"type":"broad","Text":"dog"}

String[] keyString = getParts({"type":"broad","Text":"cat"},{"type":"broad","Text":"dog"}); 
for(String part : keyString){ 
    some code here which gives like this 
    String text = "cat"; 
    String type = "broad"; 
} 

有沒有人告訴我,我怎麼能得到文字和字符串

public static String[] getParts(String keyString) { 
    if(keyString.isEmpty()) 
    return null; 
    String[] parts = keyString.split(","); 
    return parts; 
} 

或者有沒有簡單的方法來獲得相應的字符串對類型。

回答

3

這看起來像JSON,所以如果你有/創建帶有字段typeText一類,你可以使用gsonJackson解析字符串並獲得該類的對象。 (您仍然可以使用split(",")分割字符串,並分析每個部分作爲單獨的JSON字符串)

+0

的一個問題但是,該數組不會以'[',']'開始或結束。 – 2010-10-14 12:27:35

+0

你是對的它是JSON字符串。最初我有這樣的JSONstring JSONString = [{「type」:「broad」,「Text」:「cat」},{「type」:「broad」,「Text」:「dog」}]在執行以下JSONArray arrayKey = new JSONArray(JSONString); arraykey = {「type」:「broad」,「Text」:「cat」},{「type」:「broad」,「Text」:「dog」} – jimmy 2010-10-14 12:32:25

+0

@salman:然後使用JSON解析器,爲了工作。 – 2010-10-14 12:40:23

2

這應該做的伎倆:

import java.util.regex.*; 

public class Test { 

    public static void main(String[] args) { 

     String input = "{\"type\":\"broad\",\"Text\":\"cat\"}," + 
         "{\"type\":\"broad\",\"Text\":\"dog\"}"; 

     System.out.println(input); 

     Pattern partPattern = Pattern.compile("\\{([^}]*)\\}"); 
     Pattern typePattern = Pattern.compile("\"type\":\"([^\"]*)\""); 
     Pattern textPattern = Pattern.compile("\"Text\":\"([^\"]*)\""); 

     Matcher m = partPattern.matcher(input); 
     while (m.find()) { 
      Matcher typeMatcher = typePattern.matcher(m.group(1)); 
      Matcher textMatcher = textPattern.matcher(m.group(1)); 

      String type = typeMatcher.find() ? typeMatcher.group(1) : "n/a"; 
      String text = textMatcher.find() ? textMatcher.group(1) : "n/a"; 

      System.out.println(type + ", " + text); 
     } 
    } 
} 

輸出ideone link):

{"type":"broad","Text":"cat"},{"type":"broad","Text":"dog"} 
broad, cat 
broad, dog 
+1

使用RegExp的+1 – 2010-10-14 12:28:01