簡體   English   中英

Java Android Studio restTemplate解析JSON

[英]Java Android Studio restTemplate parse JSON

我從URL- WooCommerce API獲取JSON。

問題是我無法在應用中解析/輸出它們。

沒有錯誤,但是它沒有顯示任何數據-僅顯示標簽。

MainActivity.java:

    package at.copy_cat.app.rest;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

public class MainActivity extends ActionBarActivity {

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

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        new HttpRequestTask().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_refresh) {
            new HttpRequestTask().execute();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }


    private class HttpRequestTask extends AsyncTask<Void, Void, Greeting> {
        @Override
        protected Greeting doInBackground(Void... params) {
            try {
                final String url = "http://copy-cat.at/api/index.json";
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());



                /**Greeting greeting = restTemplate.getForObject(url, Greeting[].class);**/
              Greeting greeting = restTemplate.getForObject(url, Greeting.class);

              /**  Greeting greeting = Arrays.asList(restTemplate.getForObject(url, Greeting[].class));**/
                RestTemplate rest = new RestTemplate();



                return greeting;
            } catch (Exception e) {
                Log.e("MainActivity", e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Greeting greeting) {
            TextView greetingIdText = (TextView) findViewById(R.id.id_value);
            TextView greetingContentText = (TextView) findViewById(R.id.content_value);
            greetingIdText.setText(greeting.getId());
            greetingContentText.setText(greeting.getContent());
        }

    }

}

Greeting.java:

package at.copy_cat.app.rest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
 * Created by Michael on 17.10.2017.
 */



@JsonIgnoreProperties(ignoreUnknown=true)

public class Greeting {

    private String products;
    public String title;


    public String getId() {
        return this.products;
    }

    public String getContent() {
        return this.title;

    }

}

使用像這樣的簡單JSON: {“ id”:161,“ content”:“ Hello,World!”},它可以正常工作,但此處不能使用生成的JSON。

是的,它是一個.php文件,但我在Java代碼中使用了.json,其輸出與PHP腳本一樣,...

問題是:如何通過ID等解析產品等信息。

非常感謝!

編輯/更新:現在看起來像這樣

package at.copy_cat.app.rest;

import android.util.Log;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
/**
 * Created by Michael on 17.10.2017.
 */



@JsonIgnoreProperties(ignoreUnknown=true)

public class Greeting {


    // getters and setters
        public  List products;

        public String getContent(){
            String convertedToString = "" + products;
            /**String[] value_split = convertedToString.split(",");**/
            String[] value_split = convertedToString.split("\\,");


            try {

                JSONArray json = new JSONArray(products);


                for(int i=0;i<json.length();i++){
                    HashMap<String, String> map = new HashMap<String, String>();
                    JSONObject e = json.getJSONObject(i);

                   /** Log.v("TEST23243235", "TESTOBJ" + e);**/
                    /**JSONArray people = e.getJSONArray("products");
                    int numOfPeople = e.getInt("images");**/
                    map.put("id",  String.valueOf(i));
                    map.put("productid", "Product ID:" + e.getString("id"));
                    map.put("title", "Title: " +  e.getString("title"));
                    map.put("permalink", "Permalink: " +  e.getString("permalink"));
                    map.put("status", "Status: " +  e.getString("status"));
                    map.put("regular_price", "Regular Price: " +  e.getString("regular_price"));
                    map.put("price", "Price: " +  e.getString("price"));
                  //  map.put("description", "Description: " +  e.getString("description"));
                  //  map.put("categories", "Categories: " +  e.getString("categories"));
                   // map.put("images", "Images: " +  e.getString("images"));


                    Log.v("TEST23243235", "TESTOBJ" + map);
                    Log.v("TEST23243235", "TESTOBJ" +  json);
                    Log.v("TEST23243235", "TESTOBJI" +  i);
                    return map.toString();
                }



                // Extract data from json and store into ArrayList as class objects

                    /**JSONObject json_data = jArray.getJSONObject(i);

                    String id = jObj.getString("id");

                    Log.d("TEST23243235", "TEST" + id);**/





            } catch (JSONException e) {
        Log.e("TEST23243235", "unexpected JSON exception", e);
        // Do something to recover ... or kill the app.

        }
            return "";


        }

        public void setProducts(List products){

            this.products = products;
        }
        public class Model {
            private String title;

            //other fields

            //getters and setters
        }





    public String getId() {
        return "1";
    }

   /** public String getContent() {
     return this.convertedToString;

    }**/

}

Logcat中的輸出

TESTOBJ{price=Price: 30.00, regular_price=Regular Price: 0.00, title=Title: Camera DS, status=Status: publish, permalink=Permalink: http://copy-cat.at/produkt/camera-ds-2, id=0, productid=Product ID:590}

TESTOBJI0

所以我現在可以從Json輸出1個產品,但不能輸出兩個或更多。...我該怎么做才能解析所有產品而不僅僅是一個?

是的,代碼不干凈-很抱歉,我正在學習... :)

您的products變量是私有的。 它必須有一個setter。 否則,傑克遜無法為其設置價值。

因此,您的json看起來像這樣:

{
    "products": [
        {title and other fields}
     ]
}

因此,您的課程應如下所示:

public class Products {
    private List<Model> products;
    // getters and setters 

    public static class Model {
        private String title;
        //other fields

        //getters and setters
    }
}

我們使用Products類作為包裝器,因為json也包裝在products字段中。

您是否知道以下事實:在鏈接的json中,您獲得了帶有對象數組的對象?

更新:

package at.copy_cat.app.rest;
import android.util.Log;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import java.util.ArrayList;
/**
 * Created by Michael on 17.10.2017.
 */



@JsonIgnoreProperties(ignoreUnknown=true)

public class Greeting {


    // getters and setters
        public ArrayList products;

        public String getContent(){
            String convertedToString = "" + products;
            String[] value_split = convertedToString.split(",");

            Log.d("TEST23243235", "TEST" + products);

            return convertedToString;


        }

        public void setProducts(ArrayList products){

            this.products = products;
        }
        public class Model {
            private String title;

            //other fields

            //getters and setters
        }





    public String getId() {
        return "1";
    }

   /** public String getContent() {
     return this.convertedToString;

    }**/

}

現在,我在應用程序和控制台中具有json輸出。 現在的問題是-輸出在〜1068個符號處停止。

這是輸出:

10-18 19:54:22.256 13706-13706/at.copy_cat.app.rest D/TEST23243235: TEST[{title=Camera DS, id=590, created_at=2014-08-18T19:58:28Z, updated_at=2017-09-05T12:48:07Z, type=variable, status=publish, downloadable=false, virtual=false, permalink=http://copy-cat.at/produkt/camera-ds-2, sku=451039, price=30.00, regular_price=0.00, sale_price=null, price_html=<span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">&euro;</span>30.00</span> &ndash; <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">&euro;</span>44.00</span>, taxable=false, tax_status=taxable, tax_class=, managing_stock=true, stock_quantity=12, in_stock=true, backorders_allowed=false, backordered=false, sold_individually=false, purchaseable=true, featured=true, visible=true, catalog_visibility=visible, on_sale=true, product_url=, button_text=, weight=0.20, dimensions={length=35, width=45, height=13, unit=cm}, shipping_required=true, shipping_taxable=true, shipping_class=box1-he, shipping_class_id=68, description=<p>Donec rutrum congue leo eget malesuada. Pellentesque in ipsum id orci porta dapibus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vivamus suscipit tortor eget felis porttitor volutpat. Vivamus suscipit tortor eget felis porttitor volutpat. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Donec sollicitudin molestie malesuada. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a.</p>
                                                                    , short_description=<p>Donec sollicitudin molestie malesuada. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula. Donec ..., reviews_allowed=true, average_rating=0.00, rating_count=0, related_ids=[125, 126, 138, 118, 140], upsell_ids=[], cross_sell_ids=[], parent_id=0, categories=[Adapters, Batteries, Cables&amp;Adapters, Camcoder Tapes &amp; Discs, Cameras, Cases, Digital Cameras, Digital SLR, Discs], tags=[], images=[{id=399, created_at=2014-08-18T13:52:46Z, updated_at=2014-08-18T13:52:46Z, src=http://copy-cat.at/wp-content/uploads/2014/06/a21.jpg, title=a2, alt=, position=0}, {id=419, created_at=2014-08-18T13:53:09Z, updated_at=2014-08-18T13:53:09Z, src=http://copy-cat.at/wp-content/uploads/2014/06/a61.jpg, title=a6, alt=, position=1}, {id=414, created_at=2014-08-18T13:53:04Z, updated_at=2014-08-18T13:53:04Z, src=http://copy-cat.at/wp-content/uploads/2014/06/a51.jpg, title=a5, alt=, position=2}, {id=409, created_at=2014-08-18T13:52:58Z, updated_at=2014-08-18T13:52:58Z, src=http://copy-cat.at/wp-content/uploads/2014/06/a41.jpg, title=a4, alt=, position=3}, {id=404, created_at=2014-08-18T13:52:52Z, updated_at=2014-08-18T13:52:52Z, src=http://copy-cat.at/wp-content/uploads/2014/06/a31.jpg, title=a3, alt=, position=4}, {id=399, created_at=2014-08-18T13:52:46Z, updated_at=2014-08-18T13:52:46Z, src=http://copy-cat.at/wp-content/uploads/2014/06/a21.jpg, title=a2, alt=, position=5}, {id=394, created_at=2014-08-18T13:52:41Z, updated_at=2014-08-18T13:52:41Z, src=http://copy-cat.at/wp-content/uploads/2014/06/a11.jpg, title=a1, alt=, position=6}], featured_src=http://copy-cat.at/wp-content/uploads/2014/06/a21.jpg, attributes=[{name=colors, slug=colors, position=0, visible=true, variation=true, options=[Black, Green]}], downloads=[], download_limit=-1, download_expiry=-1, download_type=standard, purchase_note=, total_sales=19, variations=[{id=6892, created_at=2015-01-16T09:03:52Z, updated_at=2015-01-16T09:03:52Z, downloadable=false, virtual=false, permalink=http://copy-cat.at/produkt/camera-ds-2?attribute_pa_colors=black, sku=451039, price=30.00, regular_price=35.00, sale_price=30.00, taxable=false, tax_status=taxable, tax_class=, managing_stock=parent, stock_quantity=12, in_stock=true, backordered=false, purchaseable=true, visible=true, on_sale=true, weight=0.20, dimensions={length=35, width=45, height=13, unit=cm}, shipping_class=box1-he,

它停止@ shipping_class = box1-he,。

像這樣的長度輸出http://copy-cat.at/api/index.json這是什么問題?

謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM