2

この方法で JSON 文字列を作成しましたが、動的な値を渡すことができません

String input = "{\r\n" + 
                    "    \"Level\": 0,\r\n" + 
                    "    \"Name\": \"String\",\r\n" + 
                    "    \"msgName\": \"String\",\r\n" + 
                    "    \"ActualMessage\": \"String\",\r\n" + 
                    "    \"TimeStamp\": \"/Date(-62135596800000-0000)/\"\r\n" + 
                    "}" ;

String message = "this is value  want to pass to the ActualMessage attribute " ;

I need to pass dynamic value to the ActaulMessage atribute 

方法を教えてください。

私は試行錯誤の数を試しましたが、成功できませんでした。

4

3 に答える 3

2

これに使っString.format()てみてはどうですか?たとえば、「動的な値」を渡すには、テキストでプレースホルダーを宣言します。

String input = "insert %s in the string"; // here %s is the placeholder
input = String.format(input, "value");    // replace %s with actual value

inputこれで文字列が含まれます"insert value in the string"。あなたの例では、次の行を変更します。

"    \"msgName\": \"String\",\r\n"

これを次のように置き換えます。

"    \"msgName\": \"%s\",\r\n"

これで、置換を実行できます。

input = String.format(input, message);

メソッドの最初のパラメーターにはformat()さらに多くのオプションがあり、複数の引数を渡して置き換えることができることに注意してください。クラスのドキュメントを参照してください。Formatter

于 2013-06-20T12:08:36.390 に答える
1

Json を操作したい場合は GSON を検討してください。あなたの問題は次のように対処できます。

String input = "{\r\n" + 
                    "    \"Level\": 0,\r\n" + 
                    "    \"Name\": \"String\",\r\n" + 
                    "    \"msgName\": \"MessageName\",\r\n" + 
                    "    \"ActualMessage\": \"%s\",\r\n" + 
                    "    \"TimeStamp\": \"/Date(-62135596800000-0000)/\"\r\n" + 
                    "}" ;

String message = "this is value  want to pass to the ActualMessage attribute " ;
String output=String.format(input,message);
//this will replace %s with the content of message variable.
于 2013-06-20T12:07:51.317 に答える