【问题标题】:How to store json data in String varaiables?如何将json数据存储在String变量中?
【发布时间】:2017-12-11 13:33:32
【问题描述】:

如何将json 数据存储在String 变量中。我试过了,但它显示错误。我想将json 存储在一个普通的string 之下。我尝试了很多它总是显示错误。

[  
   {  
      "order":0,
      "name":"expenseType",
      "required":true,
      "type":"text",
      "placeholder":"Expense Type"
   },
   {  
      "order":1,
      "name":"date",
      "required":true,
      "type":"text",
      "placeholder":"Expense Date"
   },
   {  
      "order":3,
      "name":"amount",
      "required":true,
      "type":"number",
      "placeholder":"Enter Amount"
   },
   {  
      "order":4,
      "name":"description",
      "required":true,
      "type":"text",
      "placeholder":"Description"
   },
   {  
      "order":5,
      "name":"imageUrls",
      "type":"fileUpload",
      "options":[ urls:string]
   }
]

错误:org.json.JSONException:字符 641 处未终止的数组

【问题讨论】:

  • 它抛出的错误是什么?
  • @Pradeep Simha 显示编译错误
  • 分享你的java代码
  • 您需要告诉我们您遇到的编译错误是什么,并向我们展示相关代码:)
  • "options":[urls:string] 不是 json。

标签: java android json


【解决方案1】:

只需在 JsonObject 上使用 toString()。

String jsonString=jsonObject.toString();

从字符串重新创建 Json 对象。

 JSONObject jsonObject=new JSONObject(jsonString);

如果您希望 Json 字符串为常量,则只需将其粘贴在双引号之间。示例 json。

{ “令牌”:“”, “类型”:“1”, “信息”:{ “类型”:1, “消息”:“消息” } }

它是字符串。

  String jsonString ="{\n" +
           "   \"token\":\"\",\n" +
           "   \"type\":\"1\",\n" +
           "   \"message\":{\n" +
           "      \"type\":1,\n" +
           "      \"message\":\"message\"\n" +
           "   }\n" +
           "}";

【讨论】:

  • 我尝试过同样的事情,先生...我收到错误Error: org.json.JSONException: Unterminated array at character 641
  • 那么我认为你的 json 无效。如果您使用的是有效的 json,请在线查看 Json Viewer
【解决方案2】:

你可以使用 GSON ,创建你的对象类

分级:

compile 'com.google.code.gson:gson:2.8.2'

Java:

Gson gson = new Gson();
String myJson = "my string json array";
List<Object> list= gson.fromJson(myJson,new TypeToken<List<Object>>(){}.getType());

Documentation

【讨论】:

  • 我确实使用了任何 asytask...只是我想存储为字符串兄弟
  • 它不是一个 asytask,Gson 是一个 Parse 数据的库,它让生活变得非常简单,Object -> Json 或 Json -> Object
猜你喜欢
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多