从字符串中获取值

时间:2014-04-10 09:01:55

标签: java string

我有字符串{"AAA":xxxxx,"BB":xxxx,"CCC":"3 xxx"},我希望得到AAABBCCC的值作为我的输出。我正在使用substring方法字符串我只能得到AAA

metaDataValue = mettaDataValue.substring(metaDataValue.indexOf("")+1,metaDataValue.indexOf(":"));

5 个答案:

答案 0 :(得分:2)

如果是JSON使用解析器。

JSONObject json = new JSONObject();
json.getString("AAA");

答案 1 :(得分:0)

使用Json Parser

jar添加到您的项目

json:{"AAA":xxxxx,"BB":xxxx,"CCC":"3 xxx"}

这样做是为了获取java中的字符串

    JSONObject json=new JSONObject(string);
    String A=json.getString("AAA");
    String B=json.getString("BBB");
    String C=json.getString("CCC");

答案 2 :(得分:0)

您可以创建包含AAA,BB和CCC属性的类

public class OutputResult {

    private String AAA;
    private String BB;
    private String CCC;

    // Getters and setters ...

然后使用例如Jackson

从json字符串中读取该对象
ObjectMapper mapper = new ObjectMapper();
OutputResult outputResult = mapper.readValue(jsonString, OutputResult.class);

答案 3 :(得分:0)

如果你只使用java,

你可以使用它。

    String str= "{\"AAA\":xxxxx,\"BB\":xxxx,\"CCC\":\"3 xxx\"}";
    String st[] = str.split("\"");
    for(int i=1;i<st.length-2;i+=2){
        System.out.println(st[i]);
    }

答案 4 :(得分:0)

假设格式良好的字符串,键中没有逗号和值,一个非常简单的解决方案可以是:

String str = ...
str = str.substring(1, str.length() - 1);     // removing the {}
String[] entries = str.split(",");            // get all the "key":value
for (String entry: entries) {
   String[] entryData = entry.split(":");     // get the key and the value
   String key = entryData[0];
   key = key.substring(1, key.length() - 1);  // removing the "" from key
   String value = entryData[1];
   System.out.println(key + " -> " + value);
}

您可以在此处测试:http://ideone.com/weEbt2

如果你想在键或值中使用逗号,我认为你必须做一个小解析器。