2015-12-22 201 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(); 
      } 

     } 

    }