0

I have string {"AAA":xxxxx,"BB":xxxx,"CCC":"3 xxx"}, and I want to get the values of AAA , BB and CCC as my output.I am using substring method of string i am able to get only AAA

metaDataValue = mettaDataValue.substring(metaDataValue.indexOf("")+1,metaDataValue.indexOf(":"));
Not a bug
  • 4,286
  • 2
  • 40
  • 80
java.1.
  • 15
  • 7

5 Answers5

2

If it is JSON use parser.

JSONObject json = new JSONObject();
json.getString("AAA");
T8Z
  • 691
  • 7
  • 17
0

Use the Json Parser

Add the jar to your project

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

Do like this to get the string in java

    JSONObject json=new JSONObject(string);
    String A=json.getString("AAA");
    String B=json.getString("BBB");
    String C=json.getString("CCC");
Nambi
  • 11,944
  • 3
  • 37
  • 49
0

You can create class that contains properties AAA, BB and CCC

public class OutputResult {

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

    // Getters and setters ...

And then read that object from json string, using for example Jackson:

ObjectMapper mapper = new ObjectMapper();
OutputResult outputResult = mapper.readValue(jsonString, OutputResult.class);
  • can u tell me how can i traverse in string?? – java.1. Apr 10 '14 at 09:12
  • First you can split string with str.split(","). Then you have array of expressions like this: "AAA":xxxx. Then you can split strings again with substring.split(":") –  Apr 10 '14 at 09:16
0

If your using only java,

you can use this.

    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]);
    }
Srinivas B
  • 1,821
  • 4
  • 17
  • 35
0

Assuming a well-formed string, with no commas in the key and the value, a very simple solution can be:

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);
}

You can test here: http://ideone.com/weEbt2

If you want to have commas in keys or values, I think you have to make a little parser.

Alberto
  • 1,569
  • 1
  • 22
  • 41
  • public void processString(String line) { metaDataValue = metaDataValue.substring(metaDataValue.indexOf("{")+1, metaDataValue.indexOf("}")); String [] splitMetaDataValue = metaDataValue.split(","); String [] tokenValue = null; for (int i = 0; i – java.1. Apr 10 '14 at 12:50