无法正确解析json文件

时间:2017-10-06 19:10:22

标签: java android json

我正在使用随机引用应用,我需要通过http连接解析ajson文件。我成功地建立了联系;并且获取json数据,但是当我尝试解析它时,似乎我没有正确映射键,值或对象。或者我可能没有使用正确的代码。任何帮助赞赏。感谢

package com.example.george.radonquote;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    Toolbar myToolbar;
    String randQuote;
    String author;
    TextView quoteTextView;
    ImageView bgImageView;
    ImageView nextImageView;
    String url = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //setting the ActionBar for the activity
        myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);

        quoteTextView = (TextView) findViewById(R.id.quote_text);
        nextImageView = (ImageView) findViewById(R.id.next_quote);

        /*onclick listener for next quote*/
        nextImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FetchQuote fetchQuote = new FetchQuote();
                fetchQuote.execute();
            }
        });
    }

    /*
    * async class to get random quote in background
    */
    class FetchQuote extends AsyncTask<Void, Void, Void> {
        String quote = "";
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(MainActivity.this,"Fetching Quote!",Toast.LENGTH_LONG).show();
        }

        /*
        * making connection and parsing json data
        */
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                URL uri = new URL(url);
                HttpURLConnection urlConnection = (HttpURLConnection) uri.openConnection();
                InputStream inputStream = urlConnection.getInputStream();
                BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
                String line = "";
                while(line != null) {
                    Log.v("line: ",line);
                    line = bf.readLine();
                    quote += line;
                }
            }
            catch (MalformedURLException ex) {
                ex.printStackTrace();
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }

            try {
                JSONArray ja = new JSONArray(quote);
                JSONObject jo = (JSONObject) ja.get(0);
                randQuote = jo.get("content").toString().replaceAll("\\<[^>]*>","");
                author = jo.get("title").toString();
                Log.v("QUOTE", randQuote+" "+author);
            }
            catch (JSONException ex){
                ex.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
//            Log.v("Post Exec", randQuote);
            quoteTextView.setText(randQuote);

        }
    }
}

Output of Service- Parsed

Output of Service- Raw

3 个答案:

答案 0 :(得分:0)

您没有从网址获取有效的json。首先纠正你的字符串,然后解析json。尝试以下代码。这只是一个临时解决方案。

try {
                String requiredString = quote.substring(quote.indexOf("(") + 1, quote.indexOf(")"));
                JSONArray ja = new JSONArray(requiredString );
                JSONObject jo = (JSONObject) ja.get(0);
                randQuote = jo.get("content").toString().replaceAll("\\<[^>]*>","");
                author = jo.get("title").toString();
                Log.v("QUOTE", randQuote+" "+author);
            }

答案 1 :(得分:0)

问题是网址中的_jsonp=mycallback参数。使用此参数会导致格式错误的JSON返回给您。

正如您在the documentation中所看到的,JSONP参数在JavaScript中用于执行回调。

由于您在Android应用中使用Java,因此无需指定回调。

您需要做的就是修改网址,以便它不会定义回调:

String url = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";

然后,响应将是有效的格式化JSON,例如:

[  
   {  
      "ID":1572,
      "title":"Si Scott",
      "content":"<p>I really like looking at design and thinking: that attention to detail must have taken absolutely ages.<\/p>\n",
      "link":"https:\/\/quotesondesign.com\/si-scott\/",
      "custom_meta":{  
         "Source":"<a href=\"http:\/\/www.formatmag.com\/art\/si-scott\/\">article<\/a>"
      }
   }
]

然后,您现有的代码应该可行。我刚测试了它,它记录了正确的响应:

10-06 12:35:52.522 4606-4624/com.example.ex V/QUOTE: Graphic designers find themselves in a role of visual dishwashers for the Information Architects&#8217; chefs.  
                                                                Gunnar Swanson

答案 2 :(得分:-1)

使用JSOUP库并按照给定的代码

String content;
content = Jsoup.parse(content).text();