2015-12-22 197 views
-2

我從本地服務器獲取此數據。如何將字符串拆分爲java中的子字符串

Bundle[{json={"productId":"4","unseenIds":[1,4,8]", 
    "id":"8","message":"You have a new request for your product"}, 
    collapse_key=do_not_collapse}] 

我有這個數據分成:

{"productId":"4","unseenIds":"[1,4,8]", 
    "id":"8","message":"You have a new request for your product"} 

我怎樣才能做到這一點?

+0

作爲數組的內部包? –

+1

其完全是一個字符串 –

+0

你的意思是,Bundle [{json = {「productId」:「4」,「unseenIds」:「[1,4,8]」,「id」:「8」,「message」:「您對您的產品有新的要求「},collapse_key = do_not_collapse}]是完全字符串的。 –

回答

0

=分開並刪除額外的東西,這將是一個骯髒的解決方案,因爲您的字符串格式不正確,我沒有找到任何好處。

假設str是你的字符串,

String tokens[] = str.split("="); 
    String result = tokens[1].replace(", collapse_key",""); 

String result = tokens[1].substring(0, (tokens[1].length() -15)); 

另一種解決辦法是這樣的,

result = str.substring(<index of first = >, str.length() - <length of unwanted string at the end>); 

//re-check indexes 
result = str.substring(13, str.length()-35); 
+0

謝謝它適合我 –

0
String json = yourString.substring(13, yourString.length() - 3); 
0
please read : 
dont parse the string !!!! 
it should be automatically 

http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/ 


<dependency> 
      <groupId>org.codehaus.jackson</groupId> 
      <artifactId>jackson-mapper-asl</artifactId> 
      <version>1.9.13</version> 
     </dependency> 


    import java.util.List; 

    public class User { 

     private String name; 
     private int age; 
     private List<String> messages; 

     //getters and setters 
    } 

    import java.io.File; 
    import java.io.IOException; 
    import java.util.ArrayList; 
    import java.util.List; 

    import org.codehaus.jackson.JsonGenerationException; 
    import org.codehaus.jackson.map.JsonMappingException; 
    import org.codehaus.jackson.map.ObjectMapper; 

    public class JacksonExample { 
     public static void main(String[] args) { 

      ObjectMapper mapper = new ObjectMapper(); 

      try { 

       // Convert JSON string from file to Object 
       User user = mapper.readValue(new File("G:\\user.json"), User.class); 
       System.out.println(user); 

       // Convert JSON string to Object 
       String jsonInString = "{\"age\":33,\"messages\":[\"msg 1\",\"msg 2\"],\"name\":\"mkyong\"}"; 
       User user1 = mapper.readValue(jsonInString, User.class); 
       System.out.println(user1); 

      } catch (JsonGenerationException e) { 
       e.printStackTrace(); 
      } catch (JsonMappingException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

     } 

    }