2016-09-16 2 views
1

나는 오류가 점점 오전 내 프로그램을 실행하면 : 내가 프로그램을 실행하면, 나는 그게 내가 '사람 때문에 내 "movies2.json는"어떻게 변경되었는지 확인 또한자바 JSON 이상한 오류

org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1] 
    at org.json.JSONTokener.syntaxError(JSONTokener.java:432) 
    at org.json.JSONObject.<init>(JSONObject.java:184) 
    at MovieLibrary.<init>(MovieLibrary.java:76) 
    at LibraryOfMovieDescriptions.main(LibraryOfMovieDescriptions.java:11) 

을 파일을 저장하기 위해 쓰기 만하면 {} 파일을 처음부터 파일로 변경 한 다음 파일을 변경합니다.

"movies2.json"에서 어떻게 끝내려고합니까?

"movies.json"는 MovieLibrary 생성자에서 사용되는 파일은 다음과 같습니다

{ "Minions Puppy": { 
"Released": "10 Dec 2013", 
"Rated": "NR", 
"Actors": ["Dave", "Gru"], 
"Plot": "Dave seeing many owners walk their dogs wants a puppy of his own. He finds a mini-UFO who becomes his pal. This short film released with Despicable Me 2 chronicles how Dave helps the UFO return home.", 
"Runtime": "4:16 min", 
"Genre": ["Animation", "Family", "Cartoon"], 
"Filename": "MinionsPuppy.mp4", 
"Title": "Minions Puppy" 
}, 
"Pretty Woman": { 
"Released": "10 Dec 1973", 
"Rated": "NR", 
"Actors": ["Roy Orbison"], 
"Plot": "One of Roys most famous songs.", 
"Runtime": "3 min", 
"Genre": ["Country Music"], 
"Filename": "RoyOrbisonPrettyWoman.mp4", 
"Title": "Pretty Woman" 
}, 
"Minions Banana Song": { 
"Released": "12 Dec 2015", 
"Rated": "PG", 
"Actors": ["Steve", "Kevin", "Bob", "Stuart"], 
"Plot": "Banana is a song sung by The Minions in the teaser trailer of Despicable Me 2. It is a parody of the Beach Boys Barbara Ann. One minion gets annoyed by another, most likely Stuart, who keeps on playing his party horn while they are singing. So, at the end, he punched Stuart.", 
"Runtime": "5 min", 
"Genre": ["Animation", "Family", "Cartoon"], 
"Filename": "MinionsBananaSong.mp4", 
"Title": "Minions Banana Song" 
}, 
"Minions Banana": { 
"Released": "12 Dec 2015", 
"Rated": "PG", 
"Actors": ["Steve", "Kevin", "Stuart"], 
"Plot": "Minions fight over a banana. In the process, they wreak havoc in the Bomb Factory.", 
"Runtime": "5 min", 
"Genre": ["Animation", "Family", "Cartoon"], 
"Filename": "MinionsBanana.mp4", 
"Title": "Minions Banana" 
}, 
"Squatters Rights": { 
"Released": "07 Jun 1946", 
"Rated": "N/A", 
"Actors": ["Dessie Flynn", "James MacDonald"], 
"Plot": "Chip-n-Dale have set up house in the wood stove of Mickeys cabin. Pluto knows they are there, but Mickey only knows his matches keep going out when he tries to light a fire.", 
"Runtime": "7 min", 
"Genre": ["Cartoon", "Animation", "Family"], 
"Filename": "MMSquattersRights.mp4", 
"Title": "Squatters Rights" 
} 
} 

그래서 난 정말 어떤 도움이나 설명을 싶어요. 미리 감사드립니다.

메인 클래스

import java.io.Serializable; 

class LibraryOfMovieDescriptions implements Serializable { 
    public static void main(String[] args){ 

    MovieLibrary movieLibrary; 
    movieLibrary = new MovieLibrary("movies.json"); 

    movieLibrary.toJsonFile("movies2.json"); 
} 
} 

import org.json.JSONException; 
import org.json.JSONObject; 
import org.json.JSONArray; 
import java.io.Serializable; 

public class MovieDescription implements Serializable { 

private String title; 
private String rating; 
private String release; 
private String runtime; 
private String plot; 
private String filename; 
private String genre; 
private String actors; 

public JSONObject toJSONObject() throws JSONException { 
    JSONObject obj = new JSONObject(); 
    obj.put("Title", title); 
    obj.put("Rated", rating); 
    obj.put("Released", release); 
    obj.put("Runtime", runtime); 
    obj.put("Plot", plot); 
    obj.put("Filename", filename); 


    JSONArray a = new JSONArray(); 
    String[] sArray = this.actors.split(" , "); 
    for(int i = 0; i < sArray.length; i++){ 
     a.put(i); 
    } 
    obj.put("Actors", a); 

    JSONArray g = new JSONArray(); 
    String[] gArray = this.genre.split(" , "); 
    for(int i = 0; i < gArray.length; i++){ 
     g.put(i); 
    } 
    obj.put("Genre", g); 

    return obj; 
} 

public MovieDescription(JSONObject jsonObj) throws JSONException{    
    this.title = jsonObj.getString("Title");  
    this.rating = jsonObj.getString("Rated"); 
    this.release = jsonObj.getString("Released"); 
    this.plot = jsonObj.getString("Plot"); 
    this.runtime = jsonObj.getString("Runtime"); 
    this.filename = jsonObj.getString("Filename"); 

    JSONArray g = jsonObj.getJSONArray("Genre"); 
    for(int i = 0; i < g.length(); i++){ 
     this.genre += g.get(i) + ", "; 
    } 

    JSONArray a = jsonObj.getJSONArray("Actors"); 
    for(int i = 0; i < a.length(); i++){ 
     this.actors += a.get(i) + ", "; 
    } 
} 

public MovieDescription(){ 
    title = " "; 
    rating = " "; 
    release = " "; 
    runtime = " "; 
    plot = " "; 
    filename = " "; 
    genre = " "; 
    actors = " "; 
} 

public MovieDescription(String title, String rating, String release, String runtime, String plot, String filename, 
         String genre, String actors){ 
    this.title = title; 
    this.rating = rating; 
    this.release = release; 
    this.runtime = runtime; 
    this.plot = plot; 
    this.filename = filename; 
    this.genre = genre; 
    this.actors = actors; 
} 

public void setTitle(String title){ 
    this.title = title; 
} 

public String getTitle(){ 
    return title; 
} 

public void setRating(String rating){ 
    this.rating = rating; 
} 

public String getRating(){ 
    return rating; 
} 

public void setRelease(String release){ 
    this.release = release; 
} 

public String getRelease(){ 
    return this.release; 
} 

public void setRuntime(String runtime){ 
    this.runtime = runtime; 
} 

public String getRuntime(){ 
    return runtime; 
} 

public void setPlot(String plot){ 
    this.plot = plot; 
} 

public String getPlot(){ 
    return plot; 
} 

public void setFilename(String filename){ 
    this.filename = filename; 
} 

public String getFilename(){ 
    return filename; 
} 

public void setGenre(String genre){ 
    this.genre = genre; 
} 

public String getGenre(){ 
    return genre; 
} 

public void setActors(String actors){ 
    this.actors = actors; 
} 

public String getActors(){ 
    return actors; 
} 

public String toString(){ 
    String string = ("Title: " + title + "\n" + "Rating: " + rating + "\n" + "Released: " + release + "\n" + 
    "Runtime: " + runtime + "\n" + "Plot: " + plot + "\n" + "Filename: " + filename + "\n" + "Genre: " + genre 
    + "\n" + "Actors: " + actors + "\n"); 

    return string; 
} 

} 

MovieLibrary 클래스

import org.json.JSONObject; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import org.json.JSONTokener; 
import java.io.Serializable; 
import java.io.ObjectOutputStream; 

public class MovieLibrary implements Serializable { 

private List<MovieDescription> movieLib = new ArrayList<MovieDescription>(); 

private int arraySize; 

public MovieLibrary(){ 
    arraySize = 0; 
} 

public boolean isEmpty(){ 
    return arraySize == 0; 
} 

public MovieDescription get(String aTitle){ 
    int i = indexOf(aTitle); 
    if(i == -1){ 
     return null; 
    } 
    return movieLib.get(i); 
} 

public boolean add(MovieDescription aClip){ 
    movieLib.add(aClip); 
    arraySize++; 
    return true; 
} 

public boolean remove(String aTitle){ 
    int i = indexOf(aTitle); 
    if(i != -1){ 
     movieLib.remove(i); 
     arraySize--; 
    } 
    return true; 
} 

public String[] getTitles(){ 
    String[] s = new String[movieLib.size()]; 
    for(int i = 0; i < movieLib.size(); i++){ 
     s[i] = movieLib.get(i).getTitle(); 
    } 
    return s; 
} 

private int indexOf(String aTitle){ 
    for(int i = 0; i < movieLib.size(); i++) 
     if(((movieLib.get(i)).getTitle()).equals(aTitle)){ 
      return i; 
     } 
    return -1; 
} 

public MovieLibrary(String jsonFile){ 

    FileInputStream in = null; 
    JSONObject jsonObj = null; 
    String[] titles; 

    try{   
     in = new FileInputStream(jsonFile); 
     jsonObj = new JSONObject(new JSONTokener(in)); 
     titles = JSONObject.getNames(jsonObj); 
     System.out.println("Adding Movies..."); 
     for(int i = 0; i < titles.length; i++){ 
      System.out.println(titles[i]); 
      JSONObject temp = jsonObj.getJSONObject(titles[i]); 
      MovieDescription movies = new MovieDescription(temp); 
      movieLib.add(movies); 
     } 
     System.out.println(movieLib); 
     in.close();   
    } 
    catch(Exception e){ 
     e.printStackTrace(); 
     if(in != null){ 
      try{ 
       in.close(); 
      } 
      catch(IOException z){ 
       z.printStackTrace(); 
       System.exit(0); 
      } 
     } 
    } 
} 

public void toJsonFile(String jsonFileName){ 

    JSONObject jsonObj = new JSONObject(); 
    ObjectOutputStream out = null; 

    try{ 
     for(int i = 0; i < movieLib.size(); i++) 
      jsonObj.put(movieLib.get(i).getTitle(),movieLib.get(i).toJSONObject()); 
     out = new ObjectOutputStream(new FileOutputStream(jsonFileName));  
     out.writeObject(jsonObj.toString()); 
     out.close(); 
    } 
    catch(Exception e){ 
     e.printStackTrace(); 
     if(out != null){ 
      try{ 
      out.close(); 
      } 
      catch(IOException z){ 
       z.printStackTrace(); 
       System.exit(0); 
      } 
     } 
    } 


} 
} 
+0

개체를 읽고 쓰는 데 Gson 또는 Jackson을 사용하는 것이 좋습니다 –

+0

@ cricket_007 Gson을 사용하도록 코드를 변경하려면 어떻게해야합니까? – Codet

+0

문서의 일부를 살펴보면 자신 만의'toJSONObject' 메소드가 필요 없다는 것을 알 수 있습니다. 그게 내가보기에 유일한 주요 변화 야. –

답변

1

당신은 텍스트를 작성하는 ObjectOutputStream 사용하지 않으 MovieDescription 등급 : 다음은 코드입니다. 직렬화 된 Java 문자열을 작성 중이며 파일 시작 부분의 이상한 문자를 설명합니다. 대신 FileWriter을 사용해보세요.

public void toJsonFile(String jsonFileName) { 

    JSONObject jsonObj = new JSONObject(); 
    FileWriter out = null; 

    try{ 
     for(int i = 0; i < movieLib.size(); i++) 
      jsonObj.put(movieLib.get(i).getTitle(),movieLib.get(i).toJSONObject()); 
     out = new FileWriter(jsonFileName); 
     out.write(jsonObj.toString()); 
     out.close(); 
    } 
    catch(Exception e){ 
     e.printStackTrace(); 
     if(out != null){ 
      try{ 
      out.close(); 
      } 
      catch(IOException z){ 
       z.printStackTrace(); 
       System.exit(0); 
      } 
     } 
    } 
} 

P. try/catch 블록을 try-with-resources statement으로 변경할 수도 있습니다.

+0

나는 당신이 추천 한 것을 했어. 나는 여전히 같은 실수를하고있다. – Codet

+0

@Codet - ObjectOutputStream에서 FileWriter로 전환했을 때 출력이 전혀 변경되지 않았습니까? 그것은 믿기 어렵다. 프로젝트를 재건 하시겠습니까? –

+0

작동했습니다! 어떤 이유로 "movies2.json"을 삭제하고 "moviesJava"라는 새 검은 색 json 파일을 만들었습니다. 정말 고맙습니다!! – Codet