2016-09-27 27 views
-3
{ 
    "Header": { 
    "AppId": "appiddfdsf324", 
    "RecId": "fdsfrecid79878_879898_8797", 
    "SecureRefId": "fsdf5679567fsd_6789678", 
    "Type": "Other", 
    "Ver": "9.0.0", 
    "StartTS": "2016-09-26:07:48.798798-04:00" 
    }, 
    "Application": { 
    "APP_OS": "Windows", 
    "APP_Runtime": ".Net67986", 
    "APP_AppName": "MPS", 
    "APP_AppVersion": "9.0.0.0", 
    "Host": "fsdhajkfh657895fsdajf", 
    "Channel": "N/A", 
    "APP_ReqId": "2f3d7987987-78987-987987-897-da" 
    }, 
    "Service": { 
    "Key": "modification process", 
    "CallType": "HGDL", 
    "Operation": "processrequest", 
    "Port": "n/a" 
    }, 
    "Results": { 
    "Elapsed": 0, 
    "Message": "Message Succesfully Deleted", 
    "TraceLevel": "Information" 
    }, 
    "Security": { 
    "Vendor": "abfsdf" 
    }, 
    "Extended_Fields": { 
    "CustomerId": "4564987987", 
    "MessageId": "768789fsdafasdf987987987fasdf", 
    "TimeElapsed": "1272.8171" 
    } 
} 

上面的字符串值我們從網站結果值中捕獲,我們將通過使用selenium webdriver獲取字符串格式。 這我需要轉換和讀取「消息」如何獲取字符串值到json中並從請求中獲取消息值

注意的值:我已經嘗試下面的代碼

JsonElement jelement = new JsonParser().parse((String) elementText); 
JsonObject jobject = jelement.getAsJsonObject(); 
jobject.getAsJsonObject("Results"); 

這上面將提供結果JSON的完整結果值,但我需要獲取的值,其是本與「消息」

回答

0

下面第一行通過使字符串創建JSONObject的[這是JSON格式的,它應該是JSON格式,否則會通過異常]

在第二行,你有一JSON對象現在,您可以從任何提取元素,

e.g to fetch the value for Message, which is an element of "Results" object which is of JSON type, 

我們可以通過訪問任何元素。並取決於你是什麼取得使用得到

e.g getString -> for getting String, 
    getInt->for getting Integer, 
    JSONObject-> for getting an JSONObject 
    getJSONArray-> for getting a JSONArray 


JSONObject jsonObj=new JSONObject(pass your String) //This converts in to JSON Object 
jsonObj.getJSONOObject("Results").getString("Message"); //As result internally itself is a JSON Object 
+0

代碼只有答案是不允許的SO。請解釋代碼的作用以及它如何回答問題,以便它對OP和將來的讀者更有用。 – JeffC