How to make a nested Json object in Java?

后端 未结 4 1945
伪装坚强ぢ
伪装坚强ぢ 2020-12-25 13:42

I want to program a nested JSON Object for my Android device, but how? I have only basic experience with Json, so I would appreciate if someone could help me with the follow

相关标签:
4条回答
  • 2020-12-25 14:01

    You need to create a JSON, and add that JSON as a parameter in your POST. To do that you should probably :

    post.add(new BasicNameValuePair("data",json.toString());
    

    You could use org.json.JSONObject, it is included in the Android SDK.

    0 讨论(0)
  • 2020-12-25 14:01

    If you just want to send a block of JSON to the server you should not use key value pairs but just post the data as a StringEntity.

        HttpPost request = new HttpPost(api_call);
    
        request.setHeader("Content-Type", "text/javascript");
        request.setEntity(new StringEntity(jsonString);
    
        httpClient.execute(request);
    
    0 讨论(0)
  • 2020-12-25 14:12

    Create a Model Class for the Json, initialize it with your data. Then use Google Gson to convert it toJson also from Json to Back to the Object. and also here are two links which make your life more Easier for using Json. Online Json Editor. You can check that generated json is in the correct format or not. http://www.jsoneditoronline.org/ And Json to POJO Generated (Model Class Generator) http://www.jsonschema2pojo.org/

    0 讨论(0)
  • 2020-12-25 14:16

    BasicNameValuePair is what you use to add POST parameters. it's a little unclear what you are asking. are you asking how, given that JSON, to submit the param values as post parameters?

    you need to first parse the JSON, then pull out the parameters, then add them to the form post, like this,

    JSONObject jo = new JSONObject(jsonString);
    JSONObject joParams = jo.getJSONObject("params");
    String username = joParams.getString("username");
    
    post.add(new BasicNameValuePair("username",username);
    

    you will of course want to do checking on the JSON to ensure the params object exists, and to ensure the username parameter exits.

    0 讨论(0)
提交回复
热议问题