2017-10-18 7 views
0

URLからJSONを取得しています - WooCommerce APIJava AndroidスタジオrestTemplate 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: { "ID":161、 "内容": "こんにちは、世界のこのような単純なJSONで

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 hereでは動作しません。

はいその.phpのファイルが、私はPHPスクリプトのような同じ出力でJavaコードで.jsonを使用して...

が質問です:どのように私はIDなどにより製品などの情報を解析することができます。

多くの感謝!

EDIT/UPDATE: 今Logcat

でこの

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; 

    }**/ 

} 

出力のようなそのルックス

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つの製品の出力ではなく、二つ以上の.. .. 私はすべての製品を解析するために何をすることができますか?

はいコードがきれいではありません - 私は:)

答えて

0

あなたproducts変数がプライベートで...学ぶことについて申し訳ありません。それはセッターを持っている必要があります。さもなければジャクソンはそれに価値を置くことはできません

だから、あなたのJSONは以下のようになります。

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

だから、あなたのクラスは、そのように見えるはずです:JSONはあまりにproductsフィールドに包まれているので

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

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

     //getters and setters 
    } 
} 

我々はラッパーとしてProductsクラスを使用します。

+0

ありがとうございますが解決策ではありません:( – user2806316

+0

@ user2806316私はちょっとチェックしました.jsonバージョンはjsonを返しません.HTMLバージョンにリダイレクトします。URLは確かですか? – Valentun

+0

URLはhttp:// copyです-cat.at/api/index.json – user2806316

0

リンクのjsonでは、オブジェクトの配列を持つオブジェクトが得られるということに気付いていますか?

+0

はい、質問istはどのようにそれを解析することができます:) – user2806316

+0

私はいつも好きですユーザーは基本的なJSONObjectクラスとJSONArrayクラスです。私はアンドロイドの開発者ページへのリンクを含んでいました。それはあなたが必要とするものですか? JSONObject:https://developer.android.com/reference/org/json/JSONObject.html JSONArray:https://developer.android.com/reference/org/json/JSONArray.html – AnotherBiscuit

0

UPDATE:

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-彼を停止します。

出力はこの長さのように叫ばれますhttp://copy-cat.at/api/index.json どうしますか?

ありがとうございます!

+0

ログcatには文字列の長さの制限があります。心配しないで、あなたのjsonは大丈夫です。また、私たちの更新を投稿しないでください。代わりにあなたの投稿を編集してください。 – Valentun

+0

あなたの新しい投稿を申し訳ありません。 – user2806316

関連する問題