【问题标题】:How to separate JSON pairs and store in sqlite database in android?如何在android中分离JSON对并存储在sqlite数据库中?
【发布时间】:2020-09-13 06:59:06
【问题描述】:

如果我有 JSON:

{"Sugar":"sweet","salt":"salty","chilly":"hot"}

我想将键放在单独的列中,将值放在数据库的单独列中。如下图所示。有可能吗?

【问题讨论】:

    标签: java android sql json sqlite


    【解决方案1】:

    如果你安装了 json1 扩展,你可以使用 table-valued function json_each() 来做这个。它完全符合您的要求,即每个 json 元素生成一行,第一列中的键和第二列中的值。

    insert into mytable(ingredients, taste)
    select * from json_each('{"Sugar":"sweet","salt":"salty","chilly":"hot"}')
    

    【讨论】:

      【解决方案2】:

      首先,添加如下maven依赖

      <dependencies>
         <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
         </dependency>
      </dependencies>
      

      那么,

      //Creating a JSONParser object
            JSONParser jsonParser = new JSONParser();
            try {
               //Parsing the contents of the JSON file
               JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("/path/to/json_file"));
               //Forming URL
               System.out.println("Contents of the JSON are: ");
               System.out.println(jsonObject.get("Sugar"));
               System.out.println(jsonObject.get("Salt"));
      }
      

      这样,您可以将键插入一列,将值插入另一列。您可以使用数组索引作为键。

      【讨论】:

        猜你喜欢
        • 2013-05-12
        • 2012-01-07
        • 2013-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-22
        • 2013-02-07
        • 2010-11-17
        相关资源
        最近更新 更多