2017-01-16 4 views
1

У меня есть этот файл JSON my JSON fileКак я могу получить значения JSON внутри итератора в Java

и я хочу в Java, чтобы отобразить в System.out содержимое этого фрагмента:

else if(jsonObject2.get("type").equals("link")){ 

      System.out.println(jsonObject2.get("tr_name")); 
      System.out.println(jsonObject2.get("tr_description")); 
      System.out.println(jsonObject2.get("tr_rules")); 
      System.out.println(jsonObject2.get("source")); 
      System.out.println(jsonObject2.get("target")); 

      } 

До сих пор Я могу получить tr_name, который LINKNAME, но так как tr_description, tr_rules, source и target более подробно я не могу получить к ним доступ. От source и target Мне нужно получить их id.

Как я могу их получить?

Мой полный код Java выглядит следующим образом:

package jsontoxml; 


import java.io.*; 

import org.json.simple.parser.JSONParser; 
import org.json.simple.*; 
import java.util.*; 


public class JacksonStreamExample { 

    public static void main(String[] args) { 
     JSONParser parser = new JSONParser(); 
    try { 
     Object obj = parser.parse(new FileReader("text.json")); 
     JSONObject jsonObject = (JSONObject) obj; 

     //Check inside the JSON array with all graph objects 
     JSONArray cells = (JSONArray) jsonObject.get("cells"); 
     //Check inside the JSON object with all graph objects 
     Iterator<JSONObject> iterator = cells.iterator(); 
     while(iterator.hasNext()){ 
     JSONObject jsonObject2 = (JSONObject) iterator.next(); 
     if(jsonObject2.get("type").equals("link")){ 

      System.out.println(jsonObject2.get("tr_name")); 
      System.out.println(jsonObject2.get("tr_description")); 
      System.out.println(jsonObject2.get("tr_rules")); 
      System.out.println(jsonObject2.get("source")); 
      System.out.println(jsonObject2.get("target")); 

      } 

     } 

    } catch (Exception e) { 

     e.printStackTrace(); 

    } 

    } 

} 

Мой выход системы до сих пор:

LINKNAME 
null 
null 
{"id":"cae4c219-c2cd-4a4b-b50c-0f269963ca24"} 
{"id":"d23133e0-e516-4f72-8127-292545d3d479"} 

ответ

1

Попробуйте ниже код -

   System.out.println(jsonObject2.get("tr_name")); 

       System.out.println(((JSONObject) ((JSONObject) jsonObject2.get("attrs")).get(".attributes")) 
         .get("tr_description")); 
       System.out.println(
         ((JSONObject) ((JSONObject) jsonObject2.get("attrs")).get(".attributes")).get("tr_rules")); 

       System.out.println(((JSONObject) jsonObject2.get("source")).get("id")); 
       System.out.println(((JSONObject) jsonObject2.get("target")).get("id")); 

Выход -

LINKNAME2 
LINKDESCRIPTION2 
null 
a53898a5-c018-45c4-bd3f-4ea4d69f58ed 
e2bd21f2-508d-44b9-9f68-e374d4fa87ea 
+0

ОПРЕДЕЛЕННО YESSSSSSSSS !!!! ЭТО СРАБОТАЛО!!! СПАСИБО!!! –

Смежные вопросы