Skip to content

Instantly share code, notes, and snippets.

@Viacheslav77
Created October 17, 2016 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Viacheslav77/b8db2f91da56e35c276a0f175915984b to your computer and use it in GitHub Desktop.
Save Viacheslav77/b8db2f91da56e35c276a0f175915984b to your computer and use it in GitHub Desktop.
Распарсить json из файла.
package com.company.JSON;
class Adress {
private String country;
private String city;
private String street;
public String toString(){
return country +" "+ city +" "+street;
}
}
JSON прочтённый из файла:
{
"name": "Vsevolod",
"surname": "Ievgiienko",
"phones": ["044-256-78-90", "066-123-45-67"],
"sites": ["http://site1.com", "http://site2.com"],
"address": {
"country": "UA",
"city": "Kyiv",
"street": "abcd"
}
}
Результат:
Vsevolod Ievgiienko 044-256-78-90 066-123-45-67 http://site1.com http://site2.com UA Kyiv abcd
package com.company.JSON;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
class LoadJSON {
public static String load (String path) throws FileNotFoundException, IOException{
byte[] buf;
try (RandomAccessFile f = new RandomAccessFile(path, "r")){
buf = new byte[(int)f.length()];
f.read(buf);
};
System.out.println("JSON прочтённый из файла:" + "\n" + new String(buf));
return new String(buf);
}
}
package com.company.JSON;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
// Распарсить json из файла.
public class Main {
public static void main (String[] args) throws FileNotFoundException, IOException{
String result = null;
result = LoadJSON.load("d:\\1\\json.txt");
Gson gson = new GsonBuilder().create();
Person person = gson.fromJson(result, Person.class);
person.printJSON("Результат:");
}
}
package com.company.JSON;
class Person {
private String name;
private String surname;
private String [] phones;
private String [] sites;
private Adress address;
public void printJSON (String text){
System.out.println( text + "\n" + name +" "+ surname +" "+ getString (phones) +" "+ getString (sites) +" "+address);
}
public StringBuilder getString (String[] str){
StringBuilder sb = new StringBuilder();
for(String s: str)
sb.append(s + " ");
return sb;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment