IT

“BEGIN_OBJECT가 필요하지만 1 행 1 열에서 STRING이었습니다.”

lottoking 2020. 8. 19. 18:50
반응형

“BEGIN_OBJECT가 필요하지만 1 행 1 열에서 STRING이었습니다.”


이 방법이 있습니다.

public static Object parseStringToObject(String json) {
    String Object = json;
    Gson gson = new Gson();
    Object objects = gson.fromJson(object, Object.class);
    parseConfigFromObjectToString(object);
    return objects;
}

그리고 다음을 사용하여 JSON을 구문 분석하고 싶습니다.

public static void addObject(String IP, Object addObject) {
    try {
        String json = sendPostRequest("http://" + IP + ":3000/config/add_Object", ConfigJSONParser.parseConfigFromObjectToString(addObject));
        addObject = ConfigJSONParser.parseStringToObject(json);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

하지만 오류 메시지가 나타납니다.

com.google.gson.JsonSyntaxException : java.lang.IllegalStateException : BEGIN_OBJECT가 필요하지만 1 행 1 열에서 STRING이었습니다.


JSON 문자열을 보지 않아도 오류 메시지에서 클래스의 인스턴스로 구문 분석 할 올바른 구조가 아니라는 것을 알 수 있습니다.

Gson은 JSON 문자열이 객체 여는 중괄호로 시작될 것으로 예상합니다. 예 :

{

그러나 전달한 문자열은 열린 따옴표로 시작합니다.

"

서버의 잘못된 JSON은 항상 예상되는 사용 사례 여야합니다. 전송 중에 백만 가지가 잘못 될 수 있습니다. Gson은 오류 출력이 한 가지 문제를 제공하고 실제로 포착하는 예외는 다른 유형이기 때문에 약간 까다 롭습니다.

이 모든 것을 염두에두고 클라이언트 측의 적절한 수정은

try
{
  gson.fromJSON(ad, Ad.class);
  //...
}
catch (IllegalStateException | JsonSyntaxException exception)
{
  //...

서버에서받은 JSON이 잘못된 이유를 알고 싶다면 예외에서 catch 블록 내부를 살펴볼 수 있습니다. 그러나 문제가 되더라도 인터넷에서 수신하는 JSON을 수정하는 것은 클라이언트의 책임이 아닙니다.

어느 쪽이든 JSON이 잘못되었을 때 무엇을할지 결정하는 것은 클라이언트의 책임입니다. 두 가지 가능성은 JSON을 거부하고 아무것도하지 않고 다시 시도하는 것입니다.

다시 시도하려면 try / catch 블록 내부에 플래그를 설정 한 다음 try / catch 블록 외부에서 해당 플래그에 응답하는 것이 좋습니다. 중첩 된 try / catch는 Gson이 스택 추적과 일치하지 않는 예외로 우리를 혼란에 빠뜨린 방법 일 것입니다.

즉,별로 우아하게 보이지는 않지만

boolean failed = false;

try
{
  gson.fromJSON(ad, Ad.class);
  //...
}
catch (IllegalStateException | JsonSyntaxException exception)
{
  failed = true;
  //...
}

if (failed)
{
  //...

In Retrofit2, When you want to send your parameters in raw you must use Scalars.

first add this in your gradle:

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.retrofit2:converter-scalars:2.3.0'

    public interface ApiInterface {

    String URL_BASE = "http://10.157.102.22/rest/";

    @Headers("Content-Type: application/json")
    @POST("login")
    Call<User> getUser(@Body String body);

}

my SampleActivity :

   public class SampleActivity extends AppCompatActivity implements Callback<User> {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiInterface.URL_BASE)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiInterface apiInterface = retrofit.create(ApiInterface.class);


        // prepare call in Retrofit 2.0
        try {
            JSONObject paramObject = new JSONObject();
            paramObject.put("email", "sample@gmail.com");
            paramObject.put("pass", "4384984938943");

            Call<User> userCall = apiInterface.getUser(paramObject.toString());
            userCall.enqueue(this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onResponse(Call<User> call, Response<User> response) {
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
    }
}

Reference: [How to POST raw whole JSON in the body of a Retrofit request?


Maybe your JSON Object is right,but the response that you received is not your valid data.Just like when you connect the invalid WiFi,you may received a strange response < html>.....< /html> that GSON can not parse.

you may need to do some try..catch.. for this strange response to avoid crash.


I have come to share an solution. The error happened to me after forcing the notbook to hang up. possible solution clean preject.


Don't use jsonObject.toString on a JSON object.


In my case, I am Returning JSON Object as

{"data":"","message":"Attendance Saved Successfully..!!!","status":"success"}

Resolved by changing it as

{"data":{},"message":"Attendance Saved Successfully..!!!","status":"success"}

Here data is a sub JsonObject and it should starts from { not ""


Make sure you have DESERIALIZED objects like DATE/DATETIME etc. If you are directly sending JSON without deserializing it then it can cause this problem.


if your json format and variables are okay then check your database queries...even if data is saved in db correctly the actual problem might be in there...recheck your queries and try again.. Hope it helps

참고URL : https://stackoverflow.com/questions/28418662/expected-begin-object-but-was-string-at-line-1-column-1

반응형