« Raspberry Piからの語りかけ、リクエストボディの違い | トップページ | RestletでのAnnotationとは »

2020年10月 4日 (日)

JSON形式のリクエストボディからkeyとvalueを抜き出す

Raspberry Piからの話しをRestletサーバーがちゃんと聞き分けられるように作業している。

RestletのパッケージからgetEntityAsFormが削除さている。これが使えると、指定したkeyのvalueが容易に取得できるんだけれども、それが使えない。

しょうがないのでリクエストボディをgetEntityAsTextで文字列として取得してから、keyを探し出して、その直後にあるダブルクォーテーションで囲まれた文字列を抜き出すコードを書いてみた。なんだか年寄りの書いた古臭いコードだけれども備忘録として書いておく。

ちなみにkeyは"temp"、そのvalueは文字列としての温度数値。

public String represent(Representation entity) {

   String str = getReference().getPath();
   System.out.println( str );
   int index = str.indexOf("/datain/");
   index += "/datain/".length();
   String indata = str.substring(index);
   System.out.println("keyword:" + indata );

   String key = "temp";

   String pline = getRequest().getEntityAsText();
   System.out.println("request body:"+pline); /* {"temp": "27.123"} */

   index = pline.indexOf(key+"\":");
   index += key.length() + 1;
   String temp = pline.substring(index, pline.length()); /* コロンの後の文字列 */
   System.out.println( temp );

   index = temp.indexOf("\"");
   temp = temp.substring(index+1,temp.length()); /* 最初のダブルクォーテーション以後の文字列 */
   System.out.println( temp );

   int last_index = temp.indexOf("\"");
   temp = temp.substring(0,last_index); /* 最初のダブルクォーテーションまでの文字列 */
   System.out.println("temp="+temp);   /* コロン直後のダブルクォーテーションに挟まれた文字列 */


return pline;

以上

« Raspberry Piからの語りかけ、リクエストボディの違い | トップページ | RestletでのAnnotationとは »

ラズパイ日記」カテゴリの記事

コメント

コメントを書く

(ウェブ上には掲載しません)

« Raspberry Piからの語りかけ、リクエストボディの違い | トップページ | RestletでのAnnotationとは »