Parse json format data and parse json format

Source: Internet
Author: User

Parse json format data and parse json format

Goals

Read the json format data in the file, and one row is a json format data. It is parsed and encapsulated into Entity classes.

Parse json data using google's Gson object

The json format data I parse now is:

{"id": "1403","name": "1.2.3 Diva","has_barcode": true,"barcode_format": "EAN_13","homepage": "http://1-2-3.fr","regions": ["DE","FR"],"other_stores": [],"typos": ["un deux trois","un1deux2trois3"],"logo": "undeuxtrois","android_banner_url": "http://stocardapp.s3-external-3.amazonaws.com/android/banner/undeuxtrois.png","ios_banner_url": "http://stocardapp.s3-external-3.amazonaws.com/ios/banners/undeuxtrois.png","ios_logo_url": "http://stocardapp.s3-external-3.amazonaws.com/ios/icons/undeuxtrois@2x.png"},

Code Implementation

1. entity class

import java.util.List;public class ImportBrand{    private int id;    private String name;    private String has_barcode;    private String barcode_format;    private String homepage;    private List<String> regions;    private List<String> other_stores;    private List<String> typos;    private String logo;    private String android_banner_url;    private String ios_banner_url;    private String ios_logo_url;        @Override    public String toString()    {        // TODO Auto-generated method stub        return "id=" + id + ",name = " + name + ",has_barcode = " + has_barcode + ",barcode_format=" + barcode_format +                ",homepage =" + homepage + ",regions = " + regions +",logo = " + logo +",android_banner_url = " + android_banner_url +                ",ios_banner_url=" + ios_banner_url + ",ios_logo_url = " + ios_logo_url;    }            public int getId()    {        return id;    }    public void setId(int id)    {        this.id = id;    }    public String getName()    {        return name;    }    public void setName(String name)    {        this.name = name;    }    public String getHas_barcode()    {        return has_barcode;    }    public void setHas_barcode(String has_barcode)    {        this.has_barcode = has_barcode;    }    public String getBarcode_format()    {        return barcode_format;    }    public void setBarcode_format(String barcode_format)    {        this.barcode_format = barcode_format;    }    public String getHomepage()    {        return homepage;    }    public void setHomepage(String homepage)    {        this.homepage = homepage;    }            public List<String> getRegions()    {        return regions;    }    public void setRegions(List<String> regions)    {        this.regions = regions;    }    public List<String> getOther_stores()    {        return other_stores;    }    public void setOther_stores(List<String> other_stores)    {        this.other_stores = other_stores;    }    public List<String> getTypos()    {        return typos;    }    public void setTypos(List<String> typos)    {        this.typos = typos;    }    public String getLogo()    {        return logo;    }    public void setLogo(String logo)    {        this.logo = logo;    }    public String getAndroid_banner_url()    {        return android_banner_url;    }    public void setAndroid_banner_url(String android_banner_url)    {        this.android_banner_url = android_banner_url;    }    public String getIos_banner_url()    {        return ios_banner_url;    }    public void setIos_banner_url(String ios_banner_url)    {        this.ios_banner_url = ios_banner_url;    }    public String getIos_logo_url()    {        return ios_logo_url;    }    public void setIos_logo_url(String ios_logo_url)    {        this.ios_logo_url = ios_logo_url;    }}

2. Read files

Import java. io. bufferedReader; import java. io. file; import java. io. fileInputStream; import java. io. inputStreamReader; import java. util. arrayList; import java. util. list;/*** read the file ** @ author zcr **/public class ImportFile {/*** function: Java reads the txt file content step: 1: get file handle 2 First: Get file handle as input byte code stream, you need to read this input stream * 3: after reading the input stream, you need to read the generated byte stream 4: output of one row. Readline (). Note: you need to consider the exception ** @ param filePath * file path [reaching the file: for example, D: \ aa.txt] * @ return splits the file into arrays and stores them in the list. */Public static List <String> readtxtfile1_stringarrlist (String filePath) {List <String> list = new ArrayList <String> (); try {String encoding = "UTF-8 "; file file = new File (filePath); if (file. isFile () & file. exists () {// determine whether the file exists InputStreamReader read = new InputStreamReader (new FileInputStream (file), encoding); // take into account the encoding format BufferedReader bufferedReader = new BufferedReader (read ); string l IneTxt = null; while (lineTxt = bufferedReader. readLine ())! = Null) {if (isRightFormat (lineTxt) {list. add (lineTxt. substring (lineTxt. indexOf ("{"), lineTxt. lastIndexOf (',');} read. close ();} else {System. out. println ("the specified file cannot be found");} catch (Exception e) {System. out. println ("An error occurred while reading the file content"); e. printStackTrace ();} return list;} public static void main (String argv []) {String filePath = "C: \ Users \ owner \ Desktop \ zhuoxin technology internship \ stores. json "; List <String> dataList = readtxtfile1_stringarrlist (filePath); for (int I = 0; I <dataList. size (); I ++) {System. out. println (dataList. get (I);} System. out. println (dataList. size ());} /*** determine whether the data is in a valid format * @ param jsonStr with the judged data * @ return returns whether the row is in the correct format */public static boolean isRightFormat (String jsonStr) {return jsonStr. matches ("[\ p {Space}] * [{] {1 }. * [}] {1} [,] {1 }");}}

3. method call and Test

/*** Format json data ** @ author zcr **/public class FormatJson {public static void main (String [] args) {String filePath = "C: \ Users \ owner \ Desktop \ zhuoxin technology internship \ stores. json "; List <ImportBrand> brandList = FormatJson. formatFileListToBrand (filePath); for (int I = 0; I <brandList. size (); I ++) {System. out. println (brandList. get (I);} System. out. println (brandList. size ());} /*** convert json format data to Import object * @ param jsonStr json object with conversion * @ return json format data corresponding object */public static ImportBrand formatFromJsonToObject (String jsonStr) {Gson gson = new Gson (); ImportBrand brand = gson. fromJson (jsonStr, ImportBrand. class); return brand ;} /*** convert the String-type json format to a collection of ImportBrand types * @ param jsonStrList List objects in the json format to be converted * @ return: a collection of ImportBrand objects converted from json format objects * /public static List <ImportBrand> formatStringListToBrand (List <String> jsonStrList) {List <ImportBrand> listImportBrand = new ArrayList <ImportBrand> (); int size = jsonStrList. size (); for (int I = 0; I <size; I ++) {listImportBrand. add (formatFromJsonToObject (jsonStrList. get (I);} return listImportBrand;}/*** read the file, convert data in json format to the file path read by ImportBrand * @ param filePath of the List object * @ return */public static List <ImportBrand> formatFileListToBrand (String filePath) {List <String> dataList = ImportFile. readtxtfileinclustringarrlist (filePath); List <ImportBrand> brandList = formatStringListToBrand (dataList); return brandList ;}}

Thank you for reading this article.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.