预期BEGIN_ARRAY但在第1行第5列是STRING

时间:2016-09-12 00:14:49

标签: java arrays json gson converter

我是Java / Android的新手,我正在尝试创建一个类来从url https://viacep.com.br/ws/69050110/json/查询基本的休息json,而json返回的是:

{   “cep”:“69050-110”,   “logradouro”:“Conjunto Tocantins”,   “complemento”:“”,   “bairro”:“Chapada”,   “localidade”:“玛瑙斯”,   “uf”:“AM”,   “unidade”:“”,   “ibge”:“1302603”,   “gia”:“” }

我在eclipse neon中的代码是

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ViaCEP_WebService;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import org.codehaus.jackson.annotate.JsonPropertyOrder;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 *
 * @author marcelosiedler
 */
public class HttpExemplo2 {

    private final String USER_AGENT = "Mozilla/5.0";

    public static void main(String[] args) throws Exception {

        HttpExemplo2 http = new HttpExemplo2();
    //http.sendGet();

        System.out.println("Testing 1 - Send Http GET request");
        String WSChamada;
        String tipo;
        String cep;
        int array = 5;

        //WSChamada = "http://192.168.0.245:8080/datasnap/rest/TContatoController/ParcelaS/BRAA-007809-004";

        tipo = "json";
        cep = "69050110";

        WSChamada = "http://viacep.com.br/ws/"+cep+"/"+tipo;

        String json = http.sendGet(WSChamada);


        System.out.println(json); // imprimme padrão 

        // criando array de json para gson para impresão
        Gson g = new Gson();
        ConsultaWSCep c = new ConsultaWSCep();

        Type ceptype = new TypeToken<List<ConsultaWSCep>>() {}.getType();
        List<ConsultaWSCep> list = g.fromJson(WSChamada, ceptype);

        System.out.println(c.getCep());

        //c = g.fromJson(json, ConsultaWSCep);

        //System.out.println(c.getCep());

        //System.out.println("\nTesting 2 - Send Http POST request");
        //http.sendPost();

    }


    // HTTP GET request
    private String sendGet(String url) throws Exception {


        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        //System.out.println(response.toString());
        return response.toString();
    }

    // HTTP POST request
    private void sendPost() throws Exception {

        String url = "https://selfsolve.apple.com/wcResults.do";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());

    }

}

但它向我返回错误:

Testing 1 - Send Http GET request

Sending 'GET' request to URL : http://viacep.com.br/ws/69050110/json
Response Code : 200
{  "cep": "69050-110",  "logradouro": "Conjunto Tocantins",  "complemento": "",  "bairro": "Chapada",  "localidade": "Manaus",  "uf": "AM",  "unidade": "",  "ibge": "1302603",  "gia": ""}
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 5
    at com.google.gson.Gson.fromJson(Gson.java:806)
    at com.google.gson.Gson.fromJson(Gson.java:761)
    at com.google.gson.Gson.fromJson(Gson.java:710)
    at ViaCEP_WebService.HttpExemplo2.main(HttpExemplo2.java:61)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 5
    at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
    at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:306)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:79)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
    at com.google.gson.Gson.fromJson(Gson.java:795)
    ... 3 more

我想获得像cep,logadouro,complemento等对象。

任何帮助?

最佳

安德森

1 个答案:

答案 0 :(得分:0)

你要求Gson构建一个ConsultaWSCep列表,但是你的JSON只包含一个对象。

取而代之:

ConsultaWSCep consultaWSCep = g.fromJson(WSChamada, ConsultaWSCep.class);

使用:

String json = "[{  \"cep\": \"69050-110\",  \"logradouro\": \"Conjunto Tocantins\",  \"complemento\": \"\",  \"bairro\": \"Chapada\",  \"localidade\": \"Manaus\",  \"uf\": \"AM\",  \"unidade\": \"\",  \"ibge\": \"1302603\",  \"gia\": \"\"}]";

会给你你班级的单个实例(可能你的JSON确实与你的班级匹配,但由于你没有在你的问题中包含这个班级,所以很难说。

或者,更改服务器代码,使其返回数组而不是单个对象。你可以通过硬编码你的json来测试这个:

String json = http.sendGet(WSChamada);
System.out.println(json); // imprimme padrão 
// criando array de json para gson para impresão
Gson g = new Gson();
ConsultaWSCep c = g.fromJson(WSChamada, ConsultaWSCep.class);
System.out.println(c.getCep());

更完整的例子:

ConsultaWSCep c = (new Gson()).fromJson(http.sendGet(WSChamada), ConsultaWSCep.class);
System.out.println(c.getCep());

或者:

var finalOutputStrings = new List<string>();
foreach (string word in words)
{
    wordNumCount++;
    // Lowercase the input word to recognise capitals
    var s = word.ToLower();
    // List to store the found characters
    var foundChar = new List<char>();

    // Iterate around each char in the word to retain the desired order
    foreach (var character in s.Where(c => findChar.Contains(c.ToString())))
    {
        foundChar.Add(character);
    }

    // Part of the output string containing the found characters
    var charString = (foundChar.Count > 0) ? string.Join(" ", foundChar) : " _ ";

    Console.WriteLine($"({wordNumCount}) [{word}] [{charString}]");
    finalOutputStrings.Add(charString.Replace(" ", ""));
}
var outputString = string.Join(" ", finalOutputStrings);
Console.WriteLine($"Result output: [{outputString}] ");