Volley JSONArray解析有效Json上的错误

时间:2017-02-21 10:08:57

标签: java c# json asp.net-web-api2 android-volley

我试图从c#web api解析这个JsonString:

[{
"LimiteCredito": 123.00,
"PessoasFuncionarioId": 16,
"Id": 12,
"Nome": "Cliente PF A",
"DataEdicao": "\/Date(1485019536610-0200)\/",
"UsuarioAlteracaoId": "cdf23118-5991-4eb5-9ec4-ea1fc6e6ce3a",
"RazaoSocial": "Cliente PF A",
"Tipo": 1,
"Cpf": "80158536991   ",
"Sexo": "M",
"TelefonePrincipal": "(41) 9999-9999",
"Email": "comercial@datasig.com.br",
"EstadoRgId": 2,
"Apelido": "Cliente PF A",
"Erp10Id": 1,
"GrupoCrCpId": 1
}, {
    "LimiteCredito": 100.00,
    "PessoasFuncionarioId": 13,
    "Id": 15,
    "Nome": "cliente teste 3",
    "DataEdicao": "\/Date(1484849276613-0200)\/",
    "UsuarioAlteracaoId": "cdf23118-5991-4eb5-9ec4-ea1fc6e6ce3a",
    "RazaoSocial": "cliente teste 3",
    "Tipo": 2,
    "Cnpj": "20720218000128    ",
    "InscricaoEstadual": "ISENTO",
    "TelefonePrincipal": "(0",
    "Email": "cliente3@email.com.br",
    "Apelido": "cliente teste 3",
    "InscricaoMunicipal": "ISENTO",
    "Erp10Id": 1,
    "GrupoCrCpId": 1
}, {
    "LimiteCredito": 3.00,
    "Id": 43,
    "Nome": "asadvadv",
    "DataEdicao": "\/Date(1487379145870-0200)\/",
    "UsuarioAlteracaoId": "cdf23118-5991-4eb5-9ec4-ea1fc6e6ce3a",
    "RazaoSocial": "asadvadv",
    "Tipo": 1,
    "Cpf": "01234567890   ",
    "Rg": "2.231.232",
    "Sexo": "M",
    "TelefonePrincipal": "(34) 11313-1313",
    "TelefoneSecundario": "(13) 13434-1341",
    "Email": "341341341dfdf",
    "Observacao": "wdgwrg",
    "Inativa": true,
    "EstadoRgId": 1,
    "Apelido": "tes te",
    "Erp10Id": 1
}]

使用此代码会引发兼容性错误:"那不是JSONArray"

public class RegrasClienteMixForteHelper extends Request<JSONArray> {
    private Response.Listener<JSONArray> response;
    private Map<String, String> params;

    public RegrasClienteMixForteHelper(int method, String url, Map<String, String> params, Response.Listener<JSONArray> response, Response.ErrorListener listener) {
        super(method, url, listener);
        this.params = params;
        this.response = response;
    }

    public Map<String, String> getParams() throws AuthFailureError {
        return params;
    }

    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("apiKey", "application/json");

        return (header);
    }

    @Override
    protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
        try {

            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            JSONArray jsonArray = new JSONArray(jsonString);// ERROR -> this is not a JSONArray, same for JSONObject
            return Response.success(jsonArray, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void deliverResponse(JSONArray response) {
        this.response.onResponse(response);
    }
}

从我的Activity类调用该代码:

public class TesteRequisicaoActivity extends AppCompatActivity {

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

        url = "myUrl";
        queue = Volley.newRequestQueue(TesteRequisicaoActivity.this);

        callByJsonArrayRequest(null);

    }

    // CALLS VOLLEY
    public void callByJsonArrayRequest(View view) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("UserName", "userDemo");
        params.put("Password", "12345678");

        RegrasClienteMixForteHelper request = new RegrasClienteMixForteHelper(Request.Method.POST, url, params, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.i("Script", "SUCCESS: " + response);
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(TesteRequisicaoActivity.this, "Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

        request.setTag("tag");
        queue.add(request);
    }

    @Override
    public void onStop() {
        super.onStop();

        queue.cancelAll("tag");
    }

我尝试使用new Gson.parse(string).getAsJsonArray()进行解析,同样的错误,new JSONObject(string),同样的错误,我现在不知道该怎么做。

有人可以解释我该怎么做以及为什么会这样?因为响应是有效的Json。

更多信息:

  • 网络API的响应编码是默认的(我没有改变);
  • json没有换行符和标签\n\t;

1 个答案:

答案 0 :(得分:0)

所以,毕竟我已经改变了最后一件事DateTime序列化处理,我使用这个序列化:

 private string Json(object anything)
 {
    return JsonConvert.SerializeObject(anything, Formatting.None, new JsonSerializerSettings()
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        ConstructorHandling = ConstructorHandling.Default,
        DateFormatHandling = DateFormatHandling.IsoDateFormat,//Before : MicrosoftDateFormat
        DefaultValueHandling = DefaultValueHandling.Ignore,
        NullValueHandling = NullValueHandling.Ignore,
        ObjectCreationHandling = ObjectCreationHandling.Replace,
        PreserveReferencesHandling = PreserveReferencesHandling.None,
        CheckAdditionalContent = false
    });
}

我使用此方法格式化我的HTTP响应:

private HttpResponseMessage Response(object response)
{
     return new HttpResponseMessage()
    {
        Content = new StringContent(
                            Json(response),
                            System.Text.Encoding.UTF8,
                            "application/json"
                            )
    };
}

毕竟我在api控制器中的Action看起来像这样:

[HttpPost]
[Route("Clientes")]
public HttpResponseMessage GetClientes([FromBody]WebAuthModel model)
{
    SetUser(model);
    return Response(db.MyEntities.ToList().Select(x => GenericCreator.GetModel(x)));
}

这将为volley框架生成一个可解析的Json。