0

URLを使用してjsonを解析しようとしています。一時的な URL を使用して達成できますが、メイン ホストの URL を使用すると、json は html 値を返しますか?

仮URL

(http://md-plesk-web9.webhostbox.net:8880/sitepreview/http/glossymob.asia/Webservice.asmx/SpecificCategory?category=real%20estate&location=Madurai)

マイコード

// url to make request
private static String url = "http://md-plesk-web9.webhostbox.net:8880/sitepreview/http/glossymob.asia/Webservice.asmx/SpecificCategory?category=hotel&location=Madurai";

// JSON Node names
private static final String TAG_MAIN ="hotel";
private static final String TAG_VALUE = "Madurai";
private static final String TAG_ID = "id";
private static final String TAG_CATEGORY = "category";
private static final String TAG_TYPE = "type";
private static final String TAG_NAME = "name";
private static final String TAG_BANNER = "banner";
private static final String TAG_LOGO = "logo";
private static final String TAG_ABOUT = "about";
private static final String TAG_CONTACT = "contact";
private static final String TAG_MAP = "map";

private static final String TAG_MAP_LAT_LONG = "lat_long_1";
private static final String TAG_MAPLATITUDE = "latitude";
private static final String TAG_MAPLONGITUDE = "longitude";
private static final String TAG_CATEGORY_TOTAL = "total";

// contacts JSONArray
JSONArray contacts = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    Log.v("exact string value", json.toString());
    try {

        // Getting Array of Contacts
        JSONObject js= json.getJSONObject(TAG_MAIN);
        int ival = js.getInt(TAG_CATEGORY_TOTAL);
        contacts = js.getJSONArray(TAG_VALUE);
        Log.v("Total:", ""+ival);
        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String category = c.getString(TAG_CATEGORY);
            String type = c.getString(TAG_TYPE);
            String name = c.getString(TAG_NAME);
            String banner = c.getString(TAG_BANNER);
            String logo = c.getString(TAG_LOGO);
            String about = c.getString(TAG_ABOUT);
            String contact = c.getString(TAG_CONTACT);

            Log.v("Values:", id+"--"+category+"--"+type+"--"+name+"--"+banner+"--"+logo+"--"+about+"--"+contact);


            // Phone number is agin JSON Object
            JSONObject mapval = c.getJSONObject(TAG_MAP);

            JSONArray con = js.getJSONArray(TAG_VALUE);
            JSONObject mapvalues = con.getJSONObject(0);
            String latitude = mapvalues.getString(TAG_MAPLATITUDE);
            String longitude = mapvalues.getString(TAG_MAPLONGITUDE);
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);
            map.put(TAG_CATEGORY, category);
            map.put(TAG_TYPE, type);
            map.put(TAG_NAME, name);
            /*Log.v("Received json values", ""+map.toString());*/
            // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

これを実行して取得している値は正確なjsonです

01-02 12:03:38.300: V/exact string value(30124): {"hotel":{"total":1,"Madurai":[{"id":"3","logo":"www.glossymob.com\/soli\/MapMadurai\/3_logo_laptop-computer.jpg","category":"Hotel","name":"araas","map":{"lat_long_1":{"longitude":"76.9000","latitude":"8.5000"}},"about":"test","type":"Silver","contact":"test","banner":"www.glossymob.com\/soli\/MapMadurai\/3_banner_laptop-computer.jpg"}]}}
01-02 12:03:38.300: V/Total:(30124): 1
01-02 12:03:38.300: V/Values:(30124): 3--Hotel--Silver--araas--www.glossymob.com/soli/MapMadurai/3_banner_laptop-computer.jpg--www.glossymob.com/soli/MapMadurai/3_logo_laptop-computer.jpg--test--test

このメイン URL を置き換えようとすると

(http://www.glossymob.asia/Webservice.asmx/SpecificCategory?category=real%20estate&location=Madurai)

私が得ている値は

01-02 11:07:27.116: V/json string value(29330): <html>
<head> 
   <title>Runtime Error</title>    
<style>         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}          p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }         pre {font-family:"Lucida Console";font-size: .9em}         .marker {font-weight: bold; color: black;text-decoration: none;}         .version {color: gray;}         .error {margin-bottom: 10px;}         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }  
  </style>
 </head>
 <body bgcolor="white">    
    <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>            <h2> <i>Runtime Error</i> </h2></span>  
      <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">            <b> Description: </b>An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.            <br><br> 
       <b>Details:</b> To enable the details of this specific error message to be viewable on remote machines, please create a &lt;customErrors&gt; tag within a &quot;web.config&quot; configuration file located in the root directory of the current web application. This &lt;customErrors&gt; tag should then have its &quot;mode&quot; attribute set to &quot;Off&quot;.<br><br>      
  <table width=100% bgcolor="#ffffcc">               <tr>                  <td>                      <code><pre>&lt;!-- Web.Config Configuration File --&gt;&lt;configuration&gt;    &lt;system.web&gt;        &lt;customErrors mode=&quot;Off&quot;/&gt;    &lt;/system.web&gt;&lt;/configuration&gt;</pre></code>                  </td>               </tr>            </table>   
     <br>            <b>Notes:</b> The current error page you are seeing can be replaced by a custom error page by modifying the &quot;defaultRedirect&quot; attribute of the application's &lt;customErrors&gt; configuration tag to point to a custom error page URL.<br><br>          
<table width=100% bgcolor="#ffffcc">               <tr>                  <td>                      <code><pre>&lt;!-- Web.Config Configuration File --&gt;&lt;configuration&gt;    &lt;system.web&gt;        &lt;customErrors mode=&quot;RemoteOnly&quot; defaultRedirect=&quot;mycustompage.htm&quot;/&gt;    &lt;/system.web&gt;&lt;/configuration&gt;</pre></code>                  </td>               </tr>      
  </table>            <br>  
</body>
</html>

私はそのXmlデータを文字列に置き換えることで処理しています。私のjsonは正確なjson文字列値を返します。私の JSONParser クラスを見てください。パッケージcom.androidhive.jsonparsingtest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {


            line = line.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>","");
            line = line.replace("<string xmlns=\"http://tempuri.org/\">","");
            line = line.replace("</string>","");
            Log.v("string value", line);
            sb.append(line);
            //Log.v("sbstring value", sb.toString());
        }
        is.close();
        json = sb.toString();
        Log.v("json string value", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}
4

3 に答える 3

0

<string>XML内でJSON応答を取得しているため、最初にそのタグからJSONデータを取得する必要があります。

{"不動産":{"マドゥライ":[{"id": "5"、 "カテゴリ": "不動産"、 "タイプ": "シルバー"、 "名前": "ヒーラ"、 "バナー": "www.glossymob.com/soli/MapMadurai/5_banner_laptop-computer.jpg"、 "logo": "www.glossymob.com/soli/MapMadurai/5_logo_laptop-computer.jpg"、 "about": "test"、 "contact ":" test "、" map ":{"lat_long_1 ":{"latitude ":" 10.00 "、" longitude ":" 9.50 "}}}]、" total ":1}}

解決:

parse()Webからデータを受け取ったら、電話してください。

例えば:

XMLParser parser = new XMLParser();
JSONArray jsonRes = parser.parse(response.getEntity().getContent());
// response is the HTTPResponse object

XMLParserクラスは次のとおりです。

public class XMLParser extends DefaultHandler {

    private static String ROOT_ELEMENT = "string";
    private StringBuffer data = new StringBuffer();

    private JSONArray jsonData;

    public XMLParser() {
    }

    public JSONArray parse(InputStream in) {
        try {
            SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
            parser.parse(in, this);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return jsonData;
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        data.replace(0, data.length(), "");

        if (localName.equalsIgnoreCase(ROOT_ELEMENT)) {
            jsonData = new JSONArray();
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        data.append(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {

        if (localName.equalsIgnoreCase(ROOT_ELEMENT)){
            try {
                jsonData = new JSONArray(data.toString());
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


    }
}
于 2013-01-02T06:42:22.870 に答える
0

あなたの応答は:-

<string xmlns="http://tempuri.org/">
{"real estate":{"Madurai":[{"id":"5","category":"real estate","type":"Silver","name":"Heera","banner":"www.glossymob.com/soli/MapMadurai/5_banner_laptop-computer.jpg","logo":"www.glossymob.com/soli/MapMadurai/5_logo_laptop-computer.jpg","about":"test","contact":"test","map":{"lat_long_1":{"latitude":"10.00","longitude":"9.50"}}} ],"total":1} }
</string>

まず、次のように置き換える必要があります

responseString = responseString.replace("<string xmlns=\"http://tempuri.org/\">","");
responseString = responseString.replace("</string>","");

上記の行を置き換えた後、文字列を JSONObject に変換してください。

于 2013-01-02T06:40:22.890 に答える
0

純粋な JSON ではありません。その中に XML タグがあります。XML のみを使用するか、JSON を使用します。

上部と下部の XML タグを削除して、JSON の解析を進めれば簡単です。

于 2013-01-02T06:40:48.877 に答える