相关疑难解决方法(0)

如何将以下json字符串转换为java对象?

我想将以下JSON字符串转换为java对象:

String jsonString = "{
"libraryname":"My Library",
"mymusic":[{"Artist Name":"Aaron","Song Name":"Beautiful"},
{"Artist Name":"Britney","Song Name":"Oops I did It Again"},
{"Artist Name":"Britney","Song Name":"Stronger"}]}"
Run Code Online (Sandbox Code Playgroud)

我的目标是轻松访问它:

(e.g. MyJsonObject myobj = new MyJsonObject(jsonString)
myobj.mymusic[0].id would give me the ID, myobj.libraryname gives me "My Library").
Run Code Online (Sandbox Code Playgroud)

我听说过Jackson,但我不确定如何使用它来适应我所拥有的json字符串,因为它不仅仅是关键值对,因为涉及"mymusic"列表.我怎么能用杰克逊来完成这个呢?或者如果杰克逊不是最好的话,我能有更简单的方法吗?

java json jackson

56
推荐指数
3
解决办法
22万
查看次数

使用GSON的JSON字符串到Java对象

我试图将json解析为java.

根据jsonlint.com,我有以下字符串是有效的json

private final static String LOC_JSON = 
         "["
        +"{"
        +"  \"lat1\": 39.737567,"
        +"  \"lat2\": 32.7801399,"
        +"  \"long1\": -104.98471790000002,"
        +"  \"long2\": -96.80045109999998"
        +"},"
        +"  ["
        +"      {"
        +"          \"lat\": {"
        +"              \"b\": 38.88368709500021,"
        +"              \"d\": 40.620468491667026"
        +"          },"
        +"          \"long\": {"
        +"          \"b\": -105.75306170749764,"
        +"          \"d\": -104.675854661387"
        +"          }"
        +"      }"
        +"  ]"
        +"]";
Run Code Online (Sandbox Code Playgroud)

我试图将其解析为一个对象,我得到以下错误."预计BEGIN_OBJECT但在第1行第2列是BEGIN_ARRAY"

            Gson gson = new Gson();
        BoxSearch b = gson.fromJson( LOC_JSON, BoxSearch.class ); 
Run Code Online (Sandbox Code Playgroud)

BoxSearch由此组成.

private Number lat1;
private Number lat2;
private Number long1;
private Number long2; …
Run Code Online (Sandbox Code Playgroud)

java parsing json gson

16
推荐指数
2
解决办法
5万
查看次数

为什么Gson fromJson抛出一个JsonSyntaxException:预期BEGIN_OBJECT但是BEGIN_ARRAY?

(这篇文章是一个规范性的问题,下面提供了一个示例答案.)


我正在尝试将一些JSON内容反序列化为自定义POJO类型Gson#fromJson(String, Class).

这段代码

import com.google.gson.Gson;

public class Sample {
    public static void main(String[] args) {
        String json = "{\"nestedPojo\":[{\"name\":null, \"value\":42}]}";
        Gson gson = new Gson();
        gson.fromJson(json, Pojo.class);
    }
}

class Pojo {
    NestedPojo nestedPojo;
}

class NestedPojo {
    String name;
    int value;
}
Run Code Online (Sandbox Code Playgroud)

抛出以下异常

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 16 path $.nestedPojo
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:200)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)
    at com.google.gson.Gson.fromJson(Gson.java:810)
    at com.google.gson.Gson.fromJson(Gson.java:775)
    at com.google.gson.Gson.fromJson(Gson.java:724)
    at …
Run Code Online (Sandbox Code Playgroud)

java json gson

13
推荐指数
2
解决办法
4万
查看次数

编写.json文件并在Android中读取该文件

我正在写.json文件,我想读取该文件,但问题是,当我尝试将整个文件作为字符串读取时,它会在每个字符之前和之后添加空格,并且因为额外的字符,它无法读取json.

Json格式是

[{"description1":"The ThinkerA bronze sculpture by Auguste Rodin. It depicts a man in sober\nmeditation battling with a powerful internal struggle.","description2":"Steve JobsFounder of Apple, he is widely recognized as a charismatic pioneer of\nthe personal computer revolution.","description3":"Justin BieberBorn in 1994, the latest sensation in music industry with numerous\nawards in recent years."}]
Run Code Online (Sandbox Code Playgroud)

但它给出了如下的响应:[{"描述1":"他......

修剪额外的空间我引用了这个,但stil没有用: Java如何用字符串中的单个空格替换2个或更多空格并仅删除前导空格

即时通讯使用此代码

File folderPath = Environment.getExternalStorageDirectory();
File mypath=new File(folderPath, "description.json");
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(mypath));
char[] buf = new …
Run Code Online (Sandbox Code Playgroud)

string file-io android json

10
推荐指数
3
解决办法
3万
查看次数

从改造的响应错误中获取jsonBody

我正在努力改造.当我在浏览器中发布请求时,我收到了这样的请求:在此输入图像描述

这就是我的期望.但是,当我尝试在我的应用程序中解析它时,我一直得到响应,就像在这个帖子中一样.我发现尝试实现这个解决方案,但我errorBody甚至不喜欢我的浏览器的答案: 在此输入图像描述 我怎样才能获得这个JSON?

以防这是我的响应处理程序代码:

void handleResponse(Response response){
    TextView textView = (TextView)findViewById(R.id.empty_list_tv);
    if(response.isSuccessful())
        textView.setText(response.toString());
    else {
        Gson gson = new Gson();
        ErrorResponse errorResponse = gson.fromJson(
                response.errorBody().toString(),
                ErrorResponse.class);
        textView.setText(response.errorBody().toString());
    }
}
Run Code Online (Sandbox Code Playgroud)

我的ErrorResponse:

public class ErrorResponse {
    @SerializedName("message")
    private String message;
    @SerializedName("error")
    private Error error;

    public String getMessage() {
        return message;
    }

    public Error getError() {
        return error;
    }
}
Run Code Online (Sandbox Code Playgroud)

android json gson retrofit2

9
推荐指数
2
解决办法
4633
查看次数

GSON投掷"期望的名字,但在第1栏第8列是NUMBER"?

我正在尝试解析像这样的JSON字符串(使用http://www.json-generator.com生成的URL )

{
"total": 86, 
"jsonrpc": "2.0", 
"id": 1, 
"result": [
    {
        "startDate": "14/03/2012", 
        "meetingId": "1330", 
        "creator": "Jhon", 
        "lastModified": "02/04/2012", 
        "meetingTitle": "task clarification", 
        "location": "Conf hall", 
        "startTime": "02:00 PM", 
        "createdDate": "14/03/2012", 
        "owner": "Peter", 
        "endTime": "02:30 PM"
    }, 
    {
        "startDate": "20/03/2012", 
        "meetingId": "1396", 
        "creator": "Mr.Hobbs", 
        "lastModified": "07/09/2012", 
        "meetingTitle": "Design Work", 
        "location": "South conf Room", 
        "startTime": "03:30 PM", 
        "createdDate": "19/03/2012", 
        "owner": "Steve Jobs", 
        "endTime": "04:30 PM"
    }, 
    {
        "startDate": "22/03/2012", 
        "meetingId": "1432", 
        "creator": "Robin", 
        "lastModified": "21/03/2012", 
        "meetingTitle": "Do something new", …
Run Code Online (Sandbox Code Playgroud)

parsing android gson

5
推荐指数
1
解决办法
2万
查看次数

Verbose exception messages from gson?

I'm trying to parse a big chunk of JSON with gson (assisted by GsonFire). Somewhere along the way it's throwing a JsonSyntaxException.

I know what the exception means, but I'm parsing a huge file and it would really help if I could figure out which token is causing the exception. Is there a way to get more verbose output from gson?

Exception is below:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:200)
    at com.google.gson.TypeAdapter.fromJsonTree(TypeAdapter.java:281)
    at io.gsonfire.gson.FireTypeAdapter.deserialize(FireTypeAdapter.java:93)
    at io.gsonfire.gson.FireTypeAdapter.read(FireTypeAdapter.java:52) …
Run Code Online (Sandbox Code Playgroud)

java debugging json gson

5
推荐指数
1
解决办法
3184
查看次数

如何将JSON对象解析为`Map <String,HashSet <String >>`

我想解析这个JSON对象:

"{
  \"Rao\":[\"Q7293658\",\"\",\"Q7293657\",\"Q12953055\",\"Q3531237\",\"Q4178159\",\"Q1138810\",\"Q579515\",\"Q3365064\",\"Q7293664\",\"Q1133815\"],
  \"Hani Durzy\":[\"\"],
  \"Louise\":[\"\",\"Q1660645\",\"Q130413\",\"Q3215140\",\"Q152779\",\"Q233203\",\"Q7871343\",\"Q232402\",\"Q82547\",\"Q286488\",\"Q156723\",\"Q3263649\",\"Q456386\",\"Q233192\",\"Q14714149\",\"Q12125864\",\"Q57669\",\"Q168667\",\"Q141410\",\"Q166028\"],
  \"Reyna\":[\"Q7573462\",\"Q2892895\",\"Q363257\",\"Q151944\",\"Q3740321\",\"Q2857439\",\"Q1453358\",\"Q7319529\",\"Q733716\",\"Q16151941\",\"Q7159448\",\"Q5484172\",\"Q6074271\",\"Q1753185\",\"Q7319532\",\"Q5171205\",\"Q3183869\",\"Q1818527\",\"Q251862\",\"Q3840414\",\"Q5271282\",\"Q5606181\"]
}"
Run Code Online (Sandbox Code Playgroud)

并用这些数据生成一个Map<String, HashSet<String>>.

基本上我想要扭转这个过程.

这个项目的所有代码都可以在我的github页面上找到,它很短.


更新

        File f = new File("/home/matthias/Workbench/SUTD/nytimes_corpus/wdtk-parent/wdtk-examples/JSON_Output/user.json");

        String jsonTxt = null;

        if (f.exists())
        {
            InputStream is = new FileInputStream("/home/matthias/Workbench/SUTD/nytimes_corpus/wdtk-parent/wdtk-examples/JSON_Output/user.json");
            jsonTxt = IOUtils.toString(is);


        }
        //System.out.println(jsonTxt);


        Gson gson=new Gson(); 


        Map<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
        map=(Map<String, HashSet<String>>) gson.fromJson(jsonTxt, map.getClass());

        //// \\ // ! PRINT IT ! // \\ // \\ // \\ // \\ // \\ // \\
       for (Map.Entry<String, HashSet<String>> entry : map.entrySet()) …
Run Code Online (Sandbox Code Playgroud)

java json

5
推荐指数
1
解决办法
3155
查看次数

Android Retrofit没有回复

我只是刚刚改装服务的新手,并按照本教程https://www.simplifiedcoding.net/retrofit-android-tutorial-to-get-json-from-server/它运作良好,并希望创建我自己的我用一个新的JSON网络 http://api.androidhive.info/contacts/包含

{
"contacts": [
    {
            "id": "c200",
            "name": "Ravi Tamada",
            "email": "ravi@gmail.com",
            "address": "xx-xx-xxxx,x - street, x - country",
            "gender" : "male",
            "phone": {
                "mobile": "+91 0000000000",
                "home": "00 000000",
                "office": "00 000000"
            }
    },
    {
            "id": "c201",
            "name": "Johnny Depp",
            "email": "johnny_depp@gmail.com",
            "address": "xx-xx-xxxx,x - street, x - country",
            "gender" : "male",
            "phone": {
                "mobile": "+91 0000000000",
                "home": "00 000000",
                "office": "00 000000"
            }
    },
    {
            "id": "c202",
            "name": "Leonardo Dicaprio",
            "email": "leonardo_dicaprio@gmail.com",
            "address": "xx-xx-xxxx,x …
Run Code Online (Sandbox Code Playgroud)

java rest android json retrofit

5
推荐指数
1
解决办法
881
查看次数

解析Json数组导致这不是JSON数组异常

我试图解析一个看起来像这样的Json数组:

{
  "FoodItemData": [
      {
        "country": "GB",
        "id": "100",
        "name": "Steak and Kidney Pie",
        "description": "Tender cubes of steak, with tender lamb kidney is succulent rich gravy.  Served with a side of mashed potatoes and peas.",
        "category": "Dinner",
        "price": "15.95"
      },
      {
        "country": "GB",
        "id": "101",
        "name": "Toad in the Hole",
        "description": "Plump British Pork sausages backed in a light batter.  Served with mixed vegetables and a brown onion gravy.",
        "category": "Dinner",
        "price": "13.95"
      },
      {
        "country": "GB",
        "id": "102", …
Run Code Online (Sandbox Code Playgroud)

java json gson

3
推荐指数
1
解决办法
1万
查看次数

Gson 问题:- 预期为 BEGIN_OBJECT,但在第 1 行为 BEGIN_ARRAY

我对 Gson 有点陌生,我有一个以下格式的 json:-

{
  "schedulerName" : "Commodities-ETP_Trade_Entry-FO_TCP_OAS_ALSWP-COM_SLS_BZ",  
  "startRequestDate" : "29-06-2017 23:39:54.910",  
  "activeTestCasesCount" : 7,  
  "statusMap" : {    "Assigned" : 2,    "In execution" : 1,    "Pending" : 4  },  
  "subTaskCount" : 12,  
  "subTasks" : [ 
{    "testCaseName" : "OAS-TCP-ALSWP-0035",    "testCaseType" : "DealEntry",    "activeTestCase" : false,    "statuses" : [ "Excluded" ],  "currentStatus" : "Excluded",    "message" : ""  }, 
{    "testCaseName" : "OAS-TCP-ALSWP-0036",    "testCaseType" : "DealEntry",    "activeTestCase" : true,    "statuses" : [ "Pending", "Assigned", "In execution" ],    "currentStatus" : "In execution",    "message" …
Run Code Online (Sandbox Code Playgroud)

java json gson

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

json ×10

java ×8

gson ×7

android ×4

parsing ×2

debugging ×1

file-io ×1

jackson ×1

rest ×1

retrofit ×1

retrofit2 ×1

string ×1