簡體   English   中英

如何將字符串轉換為 JSONObject?

[英]How to convert string into JSONObject?

我有一個值為abc@xyz.com.的字符串abc@xyz.com. 我必須將此值傳遞給服務器,例如:

{"email":"abc@xyz.com"}

我使用okhttp將值傳遞給這樣的服務器:

Map<String, String> map = new HashMap<>();
map.put("email", email);
new PostMethodWithProgress(login_url, map, this, new Callback()
{
    @Override
    public void done(String reply)
    {
        try
        {
            JSONObject object = new JSONObject(reply);

            if (object.getString("status").equals("200"))
            {

                //Toast Success Message
            }
            else
            {
                //Toast Failure Message
            }
        }
        catch (Exception e)
        {
            Log.e("ASA", "Error is: " + e);
        }
    }
}).execute();

我該怎么做?

使用 Google Gson 輕松將字符串轉換為模型和模型到字符串
ConvertModel convertModel = new Gson().fromJson(reply, ConvertModel .class);

然后您可以輕松驗證

您可以簡單地使用JSONObject來實現這一點

JSONObject jsonObject = new JSONObject();
jsonObject.put("email", "abc@xyz.com");

String result = jsonObject.toString();

輸出:

{"email":"abc@xyz.com"}

簡單的方法是使用此代碼在 okhttp 中將 jsonobject 作為字符串傳遞

String jsonString = "";
        try {
            JSONObject obj = new JSONObject();
            obj.put("email", "abc@xyz.com");
            obj.put("pwd", "12356");

            jsonString = obj.toString();
            //out put like this -> {"email":"abc@xyz.com","pwd":"123456"}
            Log.d("JsonString__",jsonString);
        }catch (Exception e){};

JsonObject是一組可修改的名稱/值映射。 名稱是唯一的非空字符串。 值可以是JSONObjectJSONArrayStringsBooleansIntegersLongsDoublesNULL任意組合。

對於您的案例, key電子郵件valueabc@xyz.com所以正如我告訴JsonObject我們可以像下面這樣放置鍵和值對 -

JsonObject object = new JsonObject();
object.put("email","abc@xyz.com");

如果我們將上面的JsonObject轉換為字符串,那么它的值將是 -

{"email":"abc@xyz.com"}

希望這會幫助你。

用你的數據試試這個代碼。

/**
 * This method is used to create text size and color code json and store it in json object.
 *
 * @param textSize       text size entered into edit text.
 * @param colorOfPreview text color of custom text color.
 * @return return json object of created text size and color.
 */
private String createJSONObject(String textSize, int colorOfPreview) {
    JSONObject jsonObject = new JSONObject();
    try {
        // put your values here 
        jsonObject.put("textSize", textSize);
        jsonObject.put("textColor", colorOfPreview);
        return jsonObject.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jsonObject.toString();
}

暫無
暫無

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

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