1

I want to post following string as json to the server.

{ "FirstName": "John", "LastName": "Smith" }, { "FirstName": "John", "LastName": "Smith" }

But if I use below code, I am getting array list of json objects.

Gson gson = new Gson();
Type type = new TypeToken<List<Student>>() {}.getType();
String json = gson.toJson(list, type);

Output:

[{ "FirstName": "John", "LastName": "Smith" }, { "FirstName": "John", "LastName": "Smith" }]

So can anybody help me to achieve this ? Or server guy made a mistake ? I want to submit it as a post method of retrofit library.

2
  • 1
    Tell the backend Engineer, you are posting array of objects as json, so he/she will parse it accordingly Commented Sep 7, 2017 at 6:57
  • best way to pass arrayobject to server Commented Sep 7, 2017 at 7:03

2 Answers 2

2

I want to post following string as json to the server.

Suppose you use header: "content-type", "application/json"

The string you posted - is wrong JSON format:

{ "FirstName": "John", "LastName": "Smith" }, { "FirstName": "John", "LastName": "Smith" }

Your output is a right JSON syntax a.e.:

[{ "FirstName": "John", "LastName": "Smith" }, { "FirstName": "John", "LastName": "Smith" }]

So use it

Or server guy made a mistake ?

Looks like. I believe he thought about [{},{}] structure


Anyways if you want to send { "FirstName": "John", "LastName": "Smith" }, { "FirstName": "John", "LastName": "Smith" } - you have nothing to do with Gson. You got list of objects, just remove [, ] from beginning and end

private static String removeLastChar(String str) {
    return str.substring(0, str.length() - 1);
}

public String removeFirstChar(String s){
   return s.substring(1);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I know this as we have string and we can perform string operation to remove { and }, is there any correct way using gson to achieve this ? Because this is not a correct way to do, otherwise I have to ask server guy that this is not a correct way to do.
This is not possible with GSON, as the format you are asking for is not valid JSON
1

As stated by Simon, it is not a valid json as I check with JSONLint. So I talked with server guy and changed to valid json like

[{ "FirstName": "John", "LastName": "Smith" }, { "FirstName": "John", "LastName": "Smith" }]

I am posting my answer as it may help to anybody that face such type of issue in future.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.