2012-04-05 3 views
0

Мы пытаемся использовать web-сервисы в blackberry. Мы очень новичок в разработке приложений на Blackberry. После поиска в Интернете мы обнаружили, что мы можем использовать банку org.json.me для использования json webservices в blackberry, но это не работал, мы обнаружили, что мы можем использовать веб-сервисы на основе xml в BB.But, но мы не знаем, как получить и отправить данные в веб-сервис.Потребляйте веб-сервисы в Blackberry

вебсервис URL мы получили давая ответ XML является:

http://somedomainname.com/wcfservice/RestServiceImpl.svc/XML/log

Пожалуйста, руководство или предложить способ потреблять JSON/XML/ksoap веб-службы в ВВ.

любая помощь

+0

эта ссылка не возвращает XML! –

+0

Я не разместил фактический url – Shruti

+0

Отлично! Я думаю, что вы должны прочитать больше в документации BB и базе знаний, они предоставляют множество рабочих образцов, которые я тестировал, и они работают хорошо, проверьте приведенные ниже примеры в своем ответе из их базы знаний. –

ответ

1

Вот пример того, как извлечь и разобрать JSON в BB:

import net.rim.device.api.io.URI; 
import net.rim.device.api.io.messaging.*; 
import net.rim.device.api.ui.* 
import net.rim.device.api.ui.component.*; 
import net.rim.device.api.ui.container.*; 
import java.io.*; 
import org.json.me.*; 

public class NetworkSample extends UiApplication 
{ 
    public static void main(String[] args) 
    { 
     NetworkSample app = new NetworkSample(); 
     app.enterEventDispatcher(); 
    } 
    public NetworkSample() 
    { 
     pushScreen(new ParseJSONSample()); 
    } 
} 

class ParseJSONSample extends MainScreen implements FieldChangeListener 
{ 

    ButtonField _btnJSON = new ButtonField(Field.FIELD_HCENTER); 

    private static UiApplication _app = UiApplication.getUiApplication(); 

    public ParseJSONSample() 
    { 
     _btnJSON.setChangeListener(this); 
     _btnJSON.setLabel("Fetch page"); 

     add(_btnJSON); 
    } 

    public void fieldChanged(Field button, int unused) 
    { 

     if(button == _btnJSON) 
     { 

      Thread t = new Thread(new Runnable() 
      { 
       public void run() 
       { 
        Message response = null; 
        String uriStr = "http://docs.blackberry.com/sampledata.json"; 
        BlockingSenderDestination bsd = null; 
        try 
        { 
         bsd = (BlockingSenderDestination) 
            DestinationFactory.getSenderDestination 
             ("CommAPISample", URI.create(uriStr)); 
         if(bsd == null) 
         { 
          bsd = 
           DestinationFactory.createBlockingSenderDestination 
            (new Context("CommAPISample"), 
            URI.create(uriStr), new JSONMessageProcessor() 
            ); 
         } 

         // Send message and wait for response 
         response = bsd.sendReceive(); 
         _json = response.getObjectPayload(); 

         if(_json != null) 
         { 
          _app.invokeLater(new Runnable() 
          { 

           public void run() 
           { 
            _app.pushScreen(new JSONOutputScreen(_json)); 
           } 

          }); 
         } 
        } 
        catch(Exception e) 
        { 
         System.out.println(e.toString()); 
        } 
        finally 
        { 
         if(bsd != null) 
         { 
          bsd.release(); 
         } 
        } 
       } 


      }); 
      t.start(); 

     } 

} 

class JSONOutputScreen extends MainScreen implements TreeFieldCallback 
{ 

    private TreeField _treeField; 

    public JSONOutputScreen(Object JSONData) 
    { 
     _treeField = new TreeField(this, Field.FOCUSABLE); 
     add(_treeField); 
     setTree(JSONData); 
    } 

    void setTree(Object obj) 
    { 
     int parentNode = 0; 

     _treeField.deleteAll(); 

     try 
     { 
      if(obj instanceof JSONArray) 
      { 
       parentNode = populateTreeArray 
            (_treeField, (JSONArray) obj, parentNode); 
      } 
      else if(obj instanceof JSONObject) 
      { 
       parentNode = populateTreeObject 
           (_treeField, (JSONObject) obj, parentNode); 
      } 
     } 
     catch(JSONException e) 
     { 
      System.out.println(e.toString()); 
     } 

     _treeField.setCurrentNode(parentNode); 
    } 


    // Populate the trees with JSON arrays 
    int populateTreeArray(TreeField tree, JSONArray o, int p) throws JSONException 
    { 
     Object temp; 
     int newParent; 

     newParent = tree.addChildNode(p, "Array " + p); 

     for(int i = 0; i < o.length(); ++i) 
     { 
      temp = o.get(i); 

      if(temp == null || temp.toString().equalsIgnoreCase("null")) 
      { 
       continue; 
      } 

      if(temp instanceof JSONArray) 
      { 
       // Array of arrays 
       populateTreeArray(tree, (JSONArray) temp, newParent); 
      } 
      else if(temp instanceof JSONObject) 
      { 
       // Array of objects 
       populateTreeObject(tree, (JSONObject) temp, newParent); 
      } 
      else 
      { // other values 
       newParent = tree.addSiblingNode(newParent, temp.toString()); 
      } 
     } 

     return newParent; 
    } 


    // Populate the tree with JSON objects 
    int populateTreeObject(TreeField tree, JSONObject o, int p) throws JSONException 
    { 
     Object temp; 

     int newParent = tree.addChildNode(p, "Object" + p); 

     JSONArray a = o.names(); 

     for(int i = 0; i < a.length(); ++i) 
     { 
      temp = o.get(a.getString(i)); 

      if(temp == null || temp.toString().equalsIgnoreCase("null")) 
      { 
       continue; 
      } 
      if(temp instanceof JSONArray) 
      { 
       populateTreeArray(tree, (JSONArray) temp, newParent); 
      } 
      else if(temp instanceof JSONObject) 
      { 
       populateTreeObject(tree, (JSONObject) temp, newParent); 
      } 
      else 
      { 
       tree.addSiblingNode 
         (newParent, a.getString(i) + ": " + temp.toString()); 
      } 
     } 

     return newParent; 
    } 


    public void drawTreeItem(TreeField treeField, Graphics graphics, int node, 
      int y, int width, int indent) 
    { 
     if(treeField == _treeField) 
     { 
      Object cookie = _treeField.getCookie(node); 
      if(cookie instanceof String) 
      { 
       String text = (String) cookie; 
       graphics.drawText(text, indent, y, Graphics.ELLIPSIS, width); 
      } 
     } 

    } 

    public boolean onSavePrompt() 
    { 
     // Suppress the save dialog 
     return true; 
    } 

} 

Источник: http://docs.blackberry.com/en/developers/deliverables/21128/Code_sample_Parse_JSON_data_structure_1319797_11.jsp


А о том, как получать и анализировать XML в BB:

import javax.microedition.io.*; 
import net.rim.device.api.ui.*; 
import net.rim.device.api.ui.component.*; 
import net.rim.device.api.ui.container.*; 
import net.rim.device.api.system.*; 
import net.rim.device.api.xml.parsers.*; 
import org.w3c.dom.*; 
import org.xml.sax.*; 

class XML_Parsing_Sample extends UiApplication{ 
    //creating a member variable for the MainScreen 
    MainScreen _screen= new MainScreen(); 
    //string variables to store the values of the XML document 
    String _node,_element; 
    Connection _connectionthread; 

    public static void main(String arg[]){ 
     XML_Parsing_Sample application = new XML_Parsing_Sample(); 
     //create a new instance of the application 
     //and start the application on the event thread 
     application.enterEventDispatcher(); 
    } 

    public XML_Parsing_Sample() { 
     _screen.setTitle("XML Parsing");//setting title 
     _screen.add(new RichTextField("Requesting.....")); 
     _screen.add(new SeparatorField()); 
     pushScreen(_screen); // creating a screen 
     //creating a connection thread to run in the background 
     _connectionthread = new Connection(); 
     _connectionthread.start();//starting the thread operation 
    } 

    public void updateField(String node, String element){ 
     //receiving the parsed node and its value from the thread 
     //and updating it here 
     //so it can be displayed on the screen 
     String title="Title"; 
     _screen.add(new RichTextField(node+" : "+element)); 

     if(node.equals(title)){ 
      _screen.add(new SeparatorField()); 
     } 
    } 

    private class Connection extends Thread{ 
     public Connection(){ 
      super(); 
     } 

     public void run(){ 
      // define variables later used for parsing 
      Document doc; 
      StreamConnection conn; 

      try{ 
       //providing the location of the XML file, 
       //your address might be different 
       conn=(StreamConnection)Connector.open 
        ("http://localhost:8000/content/test.xml"); 
       //next few lines creates variables to open a 
       //stream, parse it, collect XML data and 
       //extract the data which is required. 
       //In this case they are elements, 
       //node and the values of an element 
       DocumentBuilderFactory docBuilderFactory 
        = DocumentBuilderFactory. newInstance(); 
       DocumentBuilder docBuilder 
        = docBuilderFactory.newDocumentBuilder(); 
       docBuilder.isValidating(); 
       doc = docBuilder.parse(conn.openInputStream()); 
       doc.getDocumentElement().normalize(); 
       NodeList list=doc.getElementsByTagName("*"); 
       _node=new String(); 
       _element = new String(); 
       //this "for" loop is used to parse through the 
       //XML document and extract all elements and their 
       //value, so they can be displayed on the device 

       for (int i=0;i<list.getLength();i++){ 
        Node value=list.item(i). 
         getChildNodes().item(0); 
        _node=list.item(i).getNodeName(); 
        _element=value.getNodeValue(); 
        updateField(_node,_element); 
       }//end for 
      }//end try 
      //will catch any exception thrown by the XML parser 
      catch (Exception e){ 
       System.out.println(e.toString()); 
      } 
     }//end connection function 
    }// end connection class 
}//end XML_Parsing_Sample 

Источник: http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/800599/How_To_-_Use_the_XML_Parser.html?nodeid=820554&vernum=0

+0

спасибо за ответ, но я не могу для импорта 'org.json.me. *;' в моем проекте blackberry – Shruti

+0

Загрузите и добавьте пакет в свой проект по этой ссылке: https://github.com/upictec/org.json.me/ –

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