将JSON转换为Java对象时出错

问题描述 投票:-3回答:2

我想将JSON转换为java对象。我创建了一个类,我写了这样的代码。我得到了异常o/p:Unexpected character (c) at position 0

我从客户端获取JSON数据。但是当我尝试将JSON转换为java时,我遇到了错误

        ClientConfig clientConfig = new DefaultClientConfig();
        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        Client client = Client.create(clientConfig);
        WebResource webResource = client
                .resource("my url");
        String name = "adn";
        String password = "12";
        String authString = name + ":" + password;
        String authStringEnc = new BASE64Encoder().encode(authString
                .getBytes());
        // System.out.println("Base64 encoded auth string: " +
        // authStringEnc);
        ClientResponse response = webResource.accept("application/json")
                .header("Authorization", "Basic " + authStringEnc)
                .get(ClientResponse.class);

        String output = response.getEntity(String.class);




         output = output.substring(13, output.length() - 1);

            System.out.println(output);

         JSONParser parse = new JSONParser(); 



counts count=new counts();

         JSONObject jobj = (JSONObject)parse.parse(output); 

         JSONArray jsonarr_1 = (JSONArray) jobj.get("Counts"); 
        // System.out.println(jsonarr_1.get(1));

         JSONArray array = new JSONArray();


        //Get data for Results array

         for(int i=0;i<jsonarr_1.length();i++)

         {

         //Store the JSON objects in an array

         //Get the index of the JSON object and print the values as per the index

         JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);


         System.out.println("Elements under results array");

         System.out.println("\nPlace id: " +jsonobj_1.get("college_name"));

         System.out.println("Types: " +jsonobj_1.get("college_epass_id"));

         }

我从客户端获取JSON数据。我想将JSON转换为java对象。我也创建了pojo(counts)课程。 json数据是这样的:

o / p:college_name“:”GPT n,Kakda“,”college_epass_id“:128},{”college_name“:”GT,am“,”college_epass_id“:2946}

错误:

位置0处的意外字符(c)。

java rest
2个回答
2
投票

使用杰克逊

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);

你的课程会有些像

public class CollegeList{
  @JsonProperty("counts")
  public List<College> counts;
}



 public class College{
     @JsonProperty("college_name") public String college_name;
     @JsonProperty("college_epass_id") public int college_epass_id;
    }

您可以将json转换为相应的对象

CollegeList colleges = mapper.readValue(jsonString, CollegeList .class);

分享Reference链接了解更多详情。


0
投票

我认为你的问题是你正在截断这一行的回应......

 output = output.substring(13, output.length() - 1);

这将使JSON字符串无效

也许你应该考虑删除这行代码或创建一个单独的变量来存储子字符串。

© www.soinside.com 2019 - 2024. All rights reserved.