ashwinsakthi
ashwinsakthi

Reputation: 1956

Parse JSON string by escaping characters

I am receiving the below string from DB.

{
    "MyDetails": {
        "Type1": "A",
        "Type2": "B",
        "Type3": "C",
        "Type4": "D",
        "Type5": "E",
        "Type6": "F",
        "Date1": "2000-02-11"
    }
}

I have created the syntax to parse JSON string but the above format is giving me an error String with which am not able to construct a String.

JSONObject obj = new JSONObject("{MYDETAILS:{TYPE: A,CLASS: B}}");
System.out.println(obj);
JSONObject array = obj.getJSONObject("MYDETAILS");
System.out.println(array);
for (int i = 0; i < array.length(); i++) {
  System.out.println(array.getString("CLASS"));
}

How do i convert the string from DB into a valid string in Java?

I guess that should give me the answer .

The problem is with the string data received from DB and am not able to convert into a String.

How to remove the quotes dynamically so that i can form a valid string?

Upvotes: 0

Views: 1223

Answers (2)

user1907906
user1907906

Reputation:

To parse this JSON

{
    "MyDetails": {
        "Type1": "A",
        "Type2": "B",
        "Type3": "C",
        "Type4": "D",
        "Type5": "E",
        "Type6": "F",
        "Date1": "2000-02-11"
    }
}

you would use something like this:

JSONObject root = ...;
JSONObject details = (JSONObject) root.get("MyDetails");
String type1 = (String) details.get("Type1");
String type2 = (String) details.get("Type2");
// and so on

Upvotes: 2

Elemental
Elemental

Reputation: 7476

Basically you are confused about JSON encoding, this string you have is a single instance of the MyDetails object and you could parse it like this:

JSONObject ob = obj.getJSONObject("MYDETAILS");
System.out.println(ob.getString("CLASS"));

If it were true that MyDetails is in fact an array then the JSON would instead use square brackets like this:

{"MyDetails": [
      {  "CLASS": "A" },
      {  "CLASS": "B"},      
    ]}

In which case your code would be:

JSONArray array = obj.getJSONArray("MYDETAILS");
System.out.println(array);
for (int i = 0; i < array.length(); i++) {
  System.out.println(array.get(i).getString("CLASS"));
}

Hope you can see the difference now.

Upvotes: 0

Related Questions