如何在Java中将字符串拆分为子字符串

时间:2015-12-22 05:47:25

标签: java substr

我从本地服务器获取此数据。

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"}

我该怎么做?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

String json = yourString.substring(13, yourString.length() - 3);

答案 2 :(得分: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();
            }

        }

    }